source: src/CodeGen/CodeGenerator.cc @ de62360d

ADTaaron-thesisarm-ehast-experimentalcleanup-dtorsctordeferred_resndemanglerenumforall-pointer-decaygc_noraiijacob/cs343-translationjenkins-sandboxmemorynew-astnew-ast-unique-exprnew-envno_listpersistent-indexerpthread-emulationqualifiedEnumresolv-newstringwith_gc
Last change on this file since de62360d was de62360d, checked in by Peter A. Buhr <pabuhr@…>, 9 years ago

fix computed goto, fixed -std=, implicit typedefs for enum and aggregates, add _Noreturn _Thread_local

  • Property mode set to 100644
File size: 17.7 KB
Line 
1//
2// Cforall Version 1.0.0 Copyright (C) 2015 University of Waterloo
3//
4// The contents of this file are covered under the licence agreement in the
5// file "LICENCE" distributed with Cforall.
6//
7// CodeGenerator.cc --
8//
9// Author           : Richard C. Bilson
10// Created On       : Mon May 18 07:44:20 2015
11// Last Modified By : Peter A. Buhr
12// Last Modified On : Tue Jun 23 16:16:57 2015
13// Update Count     : 133
14//
15
16#include <algorithm>
17#include <iostream>
18#include <cassert>
19#include <list>
20
21#include "Parser/ParseNode.h"
22
23#include "SynTree/Type.h"
24#include "SynTree/Expression.h"
25#include "SynTree/Initializer.h"
26#include "SynTree/Statement.h"
27
28#include "utility.h"
29#include "UnimplementedError.h"
30
31#include "CodeGenerator.h"
32#include "OperatorTable.h"
33#include "GenType.h"
34
35using namespace std;
36
37namespace CodeGen {
38        int CodeGenerator::tabsize = 4;
39
40        // the kinds of statements that would ideally be separated by more whitespace
41        bool wantSpacing( Statement * stmt) {
42                return dynamic_cast< IfStmt * >( stmt ) || dynamic_cast< CompoundStmt * >( stmt ) ||
43                        dynamic_cast< WhileStmt * >( stmt ) || dynamic_cast< ForStmt * > ( stmt ) || dynamic_cast< SwitchStmt *>( stmt );
44        }
45
46        CodeGenerator::CodeGenerator( std::ostream &os ) : cur_indent( 0 ), insideFunction( false ), output( os ) { }
47
48        CodeGenerator::CodeGenerator( std::ostream &os, std::string init, int indent, bool infunp )
49                        : cur_indent( indent ), insideFunction( infunp ), output( os ) {
50                //output << std::string( init );
51        }
52
53        CodeGenerator::CodeGenerator( std::ostream &os, char *init, int indent, bool infunp )
54                        : cur_indent( indent ), insideFunction( infunp ), output( os ) {
55                //output << std::string( init );
56        }
57
58        string mangleName( DeclarationWithType *decl ) {
59                if ( decl->get_mangleName() != "" ) {
60                        return decl->get_mangleName();
61                } else {
62                        return decl->get_name();
63                } // if
64        }
65 
66        //*** Declarations
67        void CodeGenerator::visit( FunctionDecl *functionDecl ) {
68                handleStorageClass( functionDecl );
69                if ( functionDecl->get_isInline() ) {
70                        output << "inline ";
71                } // if
72                if ( functionDecl->get_isNoreturn() ) {
73                        output << "_Noreturn ";
74                } // if
75                output << genType( functionDecl->get_functionType(), mangleName( functionDecl ) );
76
77                // how to get this to the Functype?
78                std::list< Declaration * > olds = functionDecl->get_oldDecls();
79                if ( ! olds.empty() ) {
80                        output << " /* function has old declaration */";
81                } // if
82
83                // acceptAll( functionDecl->get_oldDecls(), *this );
84                if ( functionDecl->get_statements() ) {
85                        functionDecl->get_statements()->accept(*this );
86                } // if
87        }
88
89        void CodeGenerator::visit( ObjectDecl *objectDecl ) {
90                handleStorageClass( objectDecl );
91                output << genType( objectDecl->get_type(), mangleName( objectDecl ) );
92       
93                if ( objectDecl->get_init() ) {
94                        output << " = ";
95                        objectDecl->get_init()->accept( *this );
96                } // if
97                if ( objectDecl->get_bitfieldWidth() ) {
98                        output << ":";
99                        objectDecl->get_bitfieldWidth()->accept( *this );
100                } // if
101        }
102
103        void CodeGenerator::handleAggregate( AggregateDecl *aggDecl ) {
104                if ( aggDecl->get_name() != "" )
105                        output << aggDecl->get_name();
106       
107                std::list< Declaration * > &memb = aggDecl->get_members();
108
109                if ( ! memb.empty() ) {
110                        output << endl << string( cur_indent, ' ' ) << "{" << endl;
111
112                        cur_indent += CodeGenerator::tabsize; 
113                        for ( std::list< Declaration* >::iterator i = memb.begin(); i != memb.end();  i++) {
114                                output << string( cur_indent, ' ' ); 
115                                (*i)->accept(*this );
116                                output << ";" << endl;
117                        }
118
119                        cur_indent -= CodeGenerator::tabsize; 
120
121                        output << string( cur_indent, ' ' ) << "}";
122                } // if
123        }
124
125        void CodeGenerator::visit( StructDecl *structDecl ) {
126                output << "struct ";
127                handleAggregate( structDecl );
128        }
129
130        void CodeGenerator::visit( UnionDecl *aggregateDecl ) {
131                output << "union ";
132                handleAggregate( aggregateDecl );
133        }
134 
135        void CodeGenerator::visit( EnumDecl *aggDecl ) {
136                output << "enum ";
137
138                if ( aggDecl->get_name() != "" )
139                        output << aggDecl->get_name();
140       
141                std::list< Declaration* > &memb = aggDecl->get_members();
142
143                if ( ! memb.empty() ) {
144                        output << endl << "{" << endl;
145
146                        cur_indent += CodeGenerator::tabsize; 
147                        for ( std::list< Declaration* >::iterator i = memb.begin(); i != memb.end();  i++) {
148                                ObjectDecl *obj = dynamic_cast< ObjectDecl* >( *i );
149                                assert( obj );
150                                output << string( cur_indent, ' ' ) << mangleName( obj ); 
151                                if ( obj->get_init() ) {
152                                        output << " = ";
153                                        obj->get_init()->accept(*this );
154                                } // if
155                                output << "," << endl;
156                        } // for
157
158                        cur_indent -= CodeGenerator::tabsize; 
159
160                        output << "}" << endl;
161                } // if
162        }
163 
164        void CodeGenerator::visit( ContextDecl *aggregateDecl ) {}
165 
166        void CodeGenerator::visit( TypedefDecl *typeDecl ) {
167                output << "typedef ";
168                output << genType( typeDecl->get_base(), typeDecl->get_name() );
169        }
170 
171        void CodeGenerator::visit( TypeDecl *typeDecl ) {
172                // really, we should mutate this into something that isn't a TypeDecl but that requires large-scale changes,
173                // still to be done
174                output << "extern unsigned long " << typeDecl->get_name();
175                if ( typeDecl->get_base() ) {
176                        output << " = sizeof( " << genType( typeDecl->get_base(), "" ) << " )";
177                } // if
178        }
179
180        void CodeGenerator::visit( SingleInit *init ) {
181                init->get_value()->accept( *this );
182        }
183
184        void CodeGenerator::visit( ListInit *init ) {
185                output << "{ ";
186                genCommaList( init->begin_initializers(), init->end_initializers() );
187                output << " }";
188        }
189
190        void CodeGenerator::visit( Constant *constant ) { 
191                output << constant->get_value() ;
192        }
193
194        //*** Expressions
195        void CodeGenerator::visit( ApplicationExpr *applicationExpr ) {
196                if ( VariableExpr *varExpr = dynamic_cast< VariableExpr* >( applicationExpr->get_function() ) ) {
197                        OperatorInfo opInfo;
198                        if ( varExpr->get_var()->get_linkage() == LinkageSpec::Intrinsic && operatorLookup( varExpr->get_var()->get_name(), opInfo ) ) {
199                                std::list< Expression* >::iterator arg = applicationExpr->get_args().begin();
200                                switch ( opInfo.type ) {
201                                  case OT_PREFIXASSIGN:
202                                  case OT_POSTFIXASSIGN:
203                                  case OT_INFIXASSIGN:
204                                        {
205                                                assert( arg != applicationExpr->get_args().end() );
206                                                if ( AddressExpr *addrExpr = dynamic_cast< AddressExpr * >( *arg ) ) {
207               
208                                                        *arg = addrExpr->get_arg();
209                                                } else {
210                                                        UntypedExpr *newExpr = new UntypedExpr( new NameExpr( "*?" ) );
211                                                        newExpr->get_args().push_back( *arg );
212                                                        *arg = newExpr;
213                                                } // if
214                                                break;
215                                        }
216             
217                                  default:
218                                        // do nothing
219                                        ;
220                                }
221           
222                                switch ( opInfo.type ) {
223                                  case OT_INDEX:
224                                        assert( applicationExpr->get_args().size() == 2 );
225                                        (*arg++)->accept( *this );
226                                        output << "[";
227                                        (*arg)->accept( *this );
228                                        output << "]";
229                                        break;
230             
231                                  case OT_CALL:
232                                        // there are no intrinsic definitions of the function call operator
233                                        assert( false );
234                                        break;
235             
236                                  case OT_PREFIX:
237                                  case OT_PREFIXASSIGN:
238                                        assert( applicationExpr->get_args().size() == 1 );
239                                        output << "(";
240                                        output << opInfo.symbol;
241                                        (*arg)->accept( *this );
242                                        output << ")";
243                                        break;
244             
245                                  case OT_POSTFIX:
246                                  case OT_POSTFIXASSIGN:
247                                        assert( applicationExpr->get_args().size() == 1 );
248                                        (*arg)->accept( *this );
249                                        output << opInfo.symbol;
250                                        break;
251
252                                  case OT_INFIX:
253                                  case OT_INFIXASSIGN:
254                                        assert( applicationExpr->get_args().size() == 2 );
255                                        output << "(";
256                                        (*arg++)->accept( *this );
257                                        output << opInfo.symbol;
258                                        (*arg)->accept( *this );
259                                        output << ")";
260                                        break;
261             
262                                  case OT_CONSTANT:
263                                        // there are no intrinsic definitions of 0 or 1 as functions
264                                        assert( false );
265                                }
266                        } else {
267                                varExpr->accept( *this );
268                                output << "(";
269                                genCommaList( applicationExpr->get_args().begin(), applicationExpr->get_args().end() );
270                                output << ")";
271                        } // if
272                } else {
273                        applicationExpr->get_function()->accept( *this );
274                        output << "(";
275                        genCommaList( applicationExpr->get_args().begin(), applicationExpr->get_args().end() );
276                        output << ")";
277                } // if
278        }
279 
280        void CodeGenerator::visit( UntypedExpr *untypedExpr ) {
281                if ( NameExpr *nameExpr = dynamic_cast< NameExpr* >( untypedExpr->get_function() ) ) {
282                        OperatorInfo opInfo;
283                        if ( operatorLookup( nameExpr->get_name(), opInfo ) ) {
284                                std::list< Expression* >::iterator arg = untypedExpr->get_args().begin();
285                                switch ( opInfo.type ) {
286                                  case OT_INDEX:
287                                        assert( untypedExpr->get_args().size() == 2 );
288                                        (*arg++)->accept( *this );
289                                        output << "[";
290                                        (*arg)->accept( *this );
291                                        output << "]";
292                                        break;
293             
294                                  case OT_CALL:
295                                        assert( false );
296                                        break;
297             
298                                  case OT_PREFIX:
299                                  case OT_PREFIXASSIGN:
300                                  case OT_LABELADDRESS:
301                                        assert( untypedExpr->get_args().size() == 1 );
302                                        output << "(";
303                                        output << opInfo.symbol;
304                                        (*arg)->accept( *this );
305                                        output << ")";
306                                        break;
307             
308                                  case OT_POSTFIX:
309                                  case OT_POSTFIXASSIGN:
310                                        assert( untypedExpr->get_args().size() == 1 );
311                                        (*arg)->accept( *this );
312                                        output << opInfo.symbol;
313                                        break;
314 
315                                  case OT_INFIX:
316                                  case OT_INFIXASSIGN:
317                                        assert( untypedExpr->get_args().size() == 2 );
318                                        output << "(";
319                                        (*arg++)->accept( *this );
320                                        output << opInfo.symbol;
321                                        (*arg)->accept( *this );
322                                        output << ")";
323                                        break;
324                                       
325                                  case OT_CONSTANT:
326                                        // there are no intrinsic definitions of 0 or 1 as functions
327                                        assert( false );
328                                }
329                        } else {
330                                nameExpr->accept( *this );
331                                output << "(";
332                                genCommaList( untypedExpr->get_args().begin(), untypedExpr->get_args().end() );
333                                output << ")";
334                        } // if
335                } else {
336                        untypedExpr->get_function()->accept( *this );
337                        output << "(";
338                        genCommaList( untypedExpr->get_args().begin(), untypedExpr->get_args().end() );
339                        output << ")";
340                } // if
341        }
342 
343        void CodeGenerator::visit( NameExpr *nameExpr ) {
344                OperatorInfo opInfo;
345                if ( operatorLookup( nameExpr->get_name(), opInfo ) ) {
346                        assert( opInfo.type == OT_CONSTANT );
347                        output << opInfo.symbol;
348                } else {
349                        output << nameExpr->get_name();
350                } // if
351        }
352 
353        void CodeGenerator::visit( AddressExpr *addressExpr ) {
354                output << "(&";
355                // this hack makes sure that we don't convert "constant_zero" to "0" if we're taking its address
356                if ( VariableExpr *variableExpr = dynamic_cast< VariableExpr* >( addressExpr->get_arg() ) ) {
357                        output << mangleName( variableExpr->get_var() );
358                } else {
359                        addressExpr->get_arg()->accept( *this );
360                } // if
361                output << ")";
362        }
363
364        void CodeGenerator::visit( CastExpr *castExpr ) {
365                output << "((";
366                if ( castExpr->get_results().empty() ) {
367                        output << "void" ;
368                } else {
369                        output << genType( castExpr->get_results().front(), "" );
370                } // if
371                output << ")";
372                castExpr->get_arg()->accept( *this );
373                output << ")";
374        }
375 
376        void CodeGenerator::visit( UntypedMemberExpr *memberExpr ) {
377                assert( false );
378        }
379 
380        void CodeGenerator::visit( MemberExpr *memberExpr ) {
381                memberExpr->get_aggregate()->accept( *this );
382                output << "." << mangleName( memberExpr->get_member() );
383        }
384 
385        void CodeGenerator::visit( VariableExpr *variableExpr ) {
386                OperatorInfo opInfo;
387                if ( variableExpr->get_var()->get_linkage() == LinkageSpec::Intrinsic && operatorLookup( variableExpr->get_var()->get_name(), opInfo ) && opInfo.type == OT_CONSTANT ) {
388                        output << opInfo.symbol;
389                } else {
390                        output << mangleName( variableExpr->get_var() );
391                } // if
392        }
393 
394        void CodeGenerator::visit( ConstantExpr *constantExpr ) {
395                assert( constantExpr->get_constant() );
396                constantExpr->get_constant()->accept( *this );
397        }
398 
399        void CodeGenerator::visit( SizeofExpr *sizeofExpr ) {
400                output << "sizeof(";
401                if ( sizeofExpr->get_isType() ) {
402                        output << genType( sizeofExpr->get_type(), "" );
403                } else {
404                        sizeofExpr->get_expr()->accept( *this );
405                } // if
406                output << ")";
407        }
408 
409        void CodeGenerator::visit( LogicalExpr *logicalExpr ) {
410                output << "(";
411                logicalExpr->get_arg1()->accept( *this );
412                if ( logicalExpr->get_isAnd() ) {
413                        output << " && ";
414                } else {
415                        output << " || ";
416                } // if
417                logicalExpr->get_arg2()->accept( *this );
418                output << ")";
419        }
420 
421        void CodeGenerator::visit( ConditionalExpr *conditionalExpr ) {
422                output << "(";
423                conditionalExpr->get_arg1()->accept( *this );
424                output << " ? ";
425                conditionalExpr->get_arg2()->accept( *this );
426                output << " : ";
427                conditionalExpr->get_arg3()->accept( *this );
428                output << ")";
429        }
430 
431        void CodeGenerator::visit( CommaExpr *commaExpr ) {
432                output << "(";
433                commaExpr->get_arg1()->accept( *this );
434                output << " , ";
435                commaExpr->get_arg2()->accept( *this );
436                output << ")";
437        }
438 
439        void CodeGenerator::visit( TupleExpr *tupleExpr ) {}
440 
441        void CodeGenerator::visit( TypeExpr *typeExpr ) {}
442
443        //*** Statements
444        void CodeGenerator::visit( CompoundStmt *compoundStmt ) {
445                std::list<Statement*> ks = compoundStmt->get_kids();
446                output << "{" << endl;
447
448                cur_indent += CodeGenerator::tabsize;
449
450                for ( std::list<Statement *>::iterator i = ks.begin(); i != ks.end();  i++) {
451                        output << string( cur_indent, ' ' ) << printLabels( (*i)->get_labels() );
452                        (*i)->accept(*this );
453
454                        output << endl;
455                        if ( wantSpacing( *i ) ) {
456                                output << endl;
457                        }
458                }
459                cur_indent -= CodeGenerator::tabsize; 
460
461                output << string( cur_indent, ' ' ) << "}";
462        }
463
464        void CodeGenerator::visit( ExprStmt *exprStmt ) {
465                // I don't see why this check is necessary.
466                // If this starts to cause problems then put it back in,
467                // with an explanation
468                assert( exprStmt );
469
470                // if ( exprStmt != 0 ) {
471                exprStmt->get_expr()->accept( *this );
472                output << ";" ;
473                // } // if
474        }
475
476        void CodeGenerator::visit( IfStmt *ifStmt ) {
477                output << "if (";
478                ifStmt->get_condition()->accept(*this );
479                output << ") ";
480
481                ifStmt->get_thenPart()->accept(*this );
482
483                if ( ifStmt->get_elsePart() != 0) {
484                        output << " else ";
485                        ifStmt->get_elsePart()->accept(*this );
486                } // if
487        }
488
489        void CodeGenerator::visit( SwitchStmt *switchStmt ) {
490                output << "switch (" ;
491                switchStmt->get_condition()->accept(*this );
492                output << ") ";
493               
494                output << "{" << std::endl;
495                cur_indent += CodeGenerator::tabsize;
496
497                acceptAll( switchStmt->get_branches(), *this );
498
499                cur_indent -= CodeGenerator::tabsize;
500
501                output << string( cur_indent, ' ' ) << "}";
502        }
503
504        void CodeGenerator::visit( CaseStmt *caseStmt ) {
505                output << string( cur_indent, ' ' );
506                if ( caseStmt->isDefault()) {
507                        output << "default";
508                } else {
509                        output << "case ";
510                        caseStmt->get_condition()->accept(*this );
511                } // if
512                output << ":\n";
513               
514                std::list<Statement *> sts = caseStmt->get_statements();
515
516                cur_indent += CodeGenerator::tabsize;
517                for ( std::list<Statement *>::iterator i = sts.begin(); i != sts.end();  i++) {
518                        output << string( cur_indent, ' ' ) << printLabels( (*i)->get_labels() )  ;
519                        (*i)->accept(*this );
520                        output << endl;
521                }
522                cur_indent -= CodeGenerator::tabsize;
523        }
524
525        void CodeGenerator::visit( BranchStmt *branchStmt ) {
526                switch ( branchStmt->get_type()) {
527                  case BranchStmt::Goto:
528                        if ( ! branchStmt->get_target().empty() )
529                                output << "goto " << branchStmt->get_target();
530                        else { 
531                                if ( branchStmt->get_computedTarget() != 0 ) {
532                                        output << "goto *";
533                                        branchStmt->get_computedTarget()->accept( *this );
534                                } // if
535                        } // if
536                        break;
537                  case BranchStmt::Break:
538                        output << "break";
539                        break;
540                  case BranchStmt::Continue:
541                        output << "continue";
542                        break;
543                }
544                output << ";";
545        }
546
547
548        void CodeGenerator::visit( ReturnStmt *returnStmt ) {
549                output << "return ";
550
551                // xxx -- check for null expression;
552                if ( returnStmt->get_expr() ) {
553                        returnStmt->get_expr()->accept( *this );
554                } // if
555                output << ";";
556        }
557
558        void CodeGenerator::visit( WhileStmt *whileStmt ) {
559                if ( whileStmt->get_isDoWhile() )
560                        output << "do" ;
561                else {
562                        output << "while (" ;
563                        whileStmt->get_condition()->accept(*this );
564                        output << ")";
565                } // if
566                output << " ";
567
568                output << CodeGenerator::printLabels( whileStmt->get_body()->get_labels() );
569                whileStmt->get_body()->accept( *this );
570
571                output << string( cur_indent, ' ' );
572
573                if ( whileStmt->get_isDoWhile() ) {
574                        output << " while (" ;
575                        whileStmt->get_condition()->accept(*this );
576                        output << ");";
577                } // if
578        }
579
580        void CodeGenerator::visit( ForStmt *forStmt ) {
581                output << "for (";
582
583                if ( forStmt->get_initialization() != 0 )
584                        forStmt->get_initialization()->accept( *this );
585                else
586                        output << ";";
587               
588                if ( forStmt->get_condition() != 0 )
589                        forStmt->get_condition()->accept( *this );
590                output << ";";
591
592                if ( forStmt->get_increment() != 0 )
593                        forStmt->get_increment()->accept( *this );
594                output << ") ";
595
596                if ( forStmt->get_body() != 0 ) {
597                        output << CodeGenerator::printLabels( forStmt->get_body()->get_labels() );
598                        forStmt->get_body()->accept( *this );
599                } // if
600        }
601
602        void CodeGenerator::visit( NullStmt *nullStmt ) {
603                //output << string( cur_indent, ' ' ) << CodeGenerator::printLabels( nullStmt->get_labels() );
604                output << "/* null statement */ ;";
605        }
606
607        void CodeGenerator::visit( DeclStmt *declStmt ) {
608                declStmt->get_decl()->accept( *this );
609       
610                if ( doSemicolon( declStmt->get_decl() ) ) {
611                        output << ";";
612                } // if
613        }
614
615        std::string CodeGenerator::printLabels( std::list< Label > &l ) {
616                std::string str( "" );
617                l.unique(); // assumes a sorted list. Why not use set?
618
619                for ( std::list< Label >::iterator i = l.begin(); i != l.end(); i++ )
620                        str += *i + ": ";
621
622                return str;
623        }
624
625        void CodeGenerator::handleStorageClass( Declaration *decl ) {
626                switch ( decl->get_storageClass() ) {
627                  case DeclarationNode::Extern:
628                        output << "extern ";
629                        break;
630                  case DeclarationNode::Static:
631                        output << "static ";
632                        break;
633                  case DeclarationNode::Auto:
634                        // silently drop storage class
635                        break;
636                  case DeclarationNode::Register:
637                        output << "register ";
638                        break;
639                  case DeclarationNode::Inline:
640                        output << "inline ";
641                        break;
642                  case DeclarationNode::Fortran:
643                        output << "fortran ";
644                        break;
645                  case DeclarationNode::Noreturn:
646                        output << "_Noreturn ";
647                        break;
648                  case DeclarationNode::Threadlocal:
649                        output << "_Thread_local ";
650                        break;
651                  case DeclarationNode::NoStorageClass:
652                        break;
653                } // switch
654        }
655} // namespace CodeGen
656
657// Local Variables: //
658// tab-width: 4 //
659// mode: c++ //
660// compile-command: "make install" //
661// End: //
Note: See TracBrowser for help on using the repository browser.