source: src/CodeGen/CodeGenerator.cc @ 4e9151f

ADTaaron-thesisarm-ehast-experimentalcleanup-dtorsdeferred_resndemanglerenumforall-pointer-decayjacob/cs343-translationjenkins-sandboxnew-astnew-ast-unique-exprnew-envno_listpersistent-indexerpthread-emulationqualifiedEnumresolv-newwith_gc
Last change on this file since 4e9151f was 5f642e38, checked in by Rob Schluntz <rschlunt@…>, 7 years ago

more work on codegen output

  • Property mode set to 100644
File size: 29.1 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 : Thu Mar 30 16:38:01 2017
13// Update Count     : 482
14//
15
16#include <algorithm>
17#include <iostream>
18#include <cassert>
19#include <list>
20
21#include "Parser/ParseNode.h"
22
23#include "SynTree/Declaration.h"
24#include "SynTree/Expression.h"
25#include "SynTree/Initializer.h"
26#include "SynTree/Statement.h"
27#include "SynTree/Type.h"
28#include "SynTree/Attribute.h"
29
30#include "Common/utility.h"
31#include "Common/UnimplementedError.h"
32
33#include "CodeGenerator.h"
34#include "OperatorTable.h"
35#include "GenType.h"
36
37#include "InitTweak/InitTweak.h"
38
39using namespace std;
40
41namespace CodeGen {
42        int CodeGenerator::tabsize = 4;
43
44        // the kinds of statements that would ideally be followed by whitespace
45        bool wantSpacing( Statement * stmt) {
46                return dynamic_cast< IfStmt * >( stmt ) || dynamic_cast< CompoundStmt * >( stmt ) ||
47                        dynamic_cast< WhileStmt * >( stmt ) || dynamic_cast< ForStmt * >( stmt ) || dynamic_cast< SwitchStmt *>( stmt );
48        }
49
50        void CodeGenerator::extension( Expression * expr ) {
51                if ( expr->get_extension() ) {
52                        output << "__extension__ ";
53                } // if
54        } // extension
55
56        void CodeGenerator::extension( Declaration * decl ) {
57                if ( decl->get_extension() ) {
58                        output << "__extension__ ";
59                } // if
60        } // extension
61
62        void CodeGenerator::asmName( DeclarationWithType * decl ) {
63                if ( ConstantExpr * asmName = decl->get_asmName() ) {
64                        output << " asm ( " << asmName->get_constant()->get_value() << " )";
65                } // if
66        } // extension
67
68        ostream & CodeGenerator::Indenter::operator()( ostream & output ) const {
69          return output << string( cg.cur_indent, ' ' );
70        }
71
72        ostream & operator<<( ostream & output, const CodeGenerator::Indenter &indent ) {
73                return indent( output );
74        }
75
76        CodeGenerator::LabelPrinter & CodeGenerator::LabelPrinter::operator()( std::list< Label > & l ) {
77                labels = &l;
78                return *this;
79        }
80
81        ostream & operator<<( ostream & output, CodeGenerator::LabelPrinter & printLabels ) {
82                std::list< Label > & labs = *printLabels.labels;
83                // l.unique(); // assumes a sorted list. Why not use set? Does order matter?
84                for ( Label & l : labs ) {
85                        output << l.get_name() + ": ";
86                        printLabels.cg.genAttributes( l.get_attributes() );
87                } // for
88                return output;
89        }
90
91        CodeGenerator::CodeGenerator( std::ostream & os, bool pretty, bool genC ) : indent( *this), cur_indent( 0 ), insideFunction( false ), output( os ), printLabels( *this ), pretty( pretty ), genC( genC ) {}
92
93        CodeGenerator::CodeGenerator( std::ostream & os, std::string init, int indentation, bool infunp )
94                        : indent( *this), cur_indent( indentation ), insideFunction( infunp ), output( os ), printLabels( *this ) {
95                //output << std::string( init );
96        }
97
98        CodeGenerator::CodeGenerator( std::ostream & os, char * init, int indentation, bool infunp )
99                        : indent( *this ), cur_indent( indentation ), insideFunction( infunp ), output( os ), printLabels( *this ) {
100                //output << std::string( init );
101        }
102
103        string CodeGenerator::mangleName( DeclarationWithType * decl ) {
104                if ( pretty ) return decl->get_name();
105                if ( decl->get_mangleName() != "" ) {
106                        // need to incorporate scope level in order to differentiate names for destructors
107                        return decl->get_scopedMangleName();
108                } else {
109                        return decl->get_name();
110                } // if
111        }
112
113        void CodeGenerator::genAttributes( list< Attribute * > & attributes ) {
114          if ( attributes.empty() ) return;
115                output << "__attribute__ ((";
116                for ( list< Attribute * >::iterator attr( attributes.begin() );; ) {
117                        output << (*attr)->get_name();
118                        if ( ! (*attr)->get_parameters().empty() ) {
119                                output << "(";
120                                genCommaList( (*attr)->get_parameters().begin(), (*attr)->get_parameters().end() );
121                                output << ")";
122                        } // if
123                  if ( ++attr == attributes.end() ) break;
124                        output << ",";                                                          // separator
125                } // for
126                output << ")) ";
127        } // CodeGenerator::genAttributes
128
129
130        //*** Declarations
131        void CodeGenerator::visit( FunctionDecl * functionDecl ) {
132                extension( functionDecl );
133                genAttributes( functionDecl->get_attributes() );
134
135                handleStorageClass( functionDecl );
136                functionDecl->get_funcSpec().print( output );
137
138                output << genType( functionDecl->get_functionType(), mangleName( functionDecl ), pretty, genC );
139
140                asmName( functionDecl );
141
142                // acceptAll( functionDecl->get_oldDecls(), *this );
143                if ( functionDecl->get_statements() ) {
144                        functionDecl->get_statements()->accept( *this );
145                } // if
146        }
147
148        void CodeGenerator::visit( ObjectDecl * objectDecl ) {
149                if (objectDecl->get_name().empty() && genC ) {
150                        // only generate an anonymous name when generating C code, otherwise it clutters the output too much
151                        static UniqueName name = { "__anonymous_object" };
152                        objectDecl->set_name( name.newName() );
153                }
154
155                extension( objectDecl );
156                genAttributes( objectDecl->get_attributes() );
157
158                handleStorageClass( objectDecl );
159                output << genType( objectDecl->get_type(), mangleName( objectDecl ), pretty, genC );
160
161                asmName( objectDecl );
162
163                if ( objectDecl->get_init() ) {
164                        output << " = ";
165                        objectDecl->get_init()->accept( *this );
166                } // if
167
168                if ( objectDecl->get_bitfieldWidth() ) {
169                        output << ":";
170                        objectDecl->get_bitfieldWidth()->accept( *this );
171                } // if
172        }
173
174        void CodeGenerator::handleAggregate( AggregateDecl * aggDecl, const std::string & kind ) {
175                genAttributes( aggDecl->get_attributes() );
176
177                if( ! aggDecl->get_parameters().empty() && ! genC ) {
178                        // assertf( ! genC, "Aggregate type parameters should not reach code generation." );
179                        output << "forall(";
180                        genCommaList( aggDecl->get_parameters().begin(), aggDecl->get_parameters().end() );
181                        output << ")" << endl;
182                }
183
184                output << kind;
185                if ( aggDecl->get_name() != "" )
186                        output << aggDecl->get_name();
187
188                if ( aggDecl->has_body() ) {
189                        std::list< Declaration * > & memb = aggDecl->get_members();
190                        output << " {" << endl;
191
192                        cur_indent += CodeGenerator::tabsize;
193                        for ( std::list< Declaration* >::iterator i = memb.begin(); i != memb.end(); i++ ) {
194                                output << indent;
195                                (*i)->accept( *this );
196                                output << ";" << endl;
197                        } // for
198
199                        cur_indent -= CodeGenerator::tabsize;
200
201                        output << indent << "}";
202                } // if
203        }
204
205        void CodeGenerator::visit( StructDecl * structDecl ) {
206                extension( structDecl );
207                handleAggregate( structDecl, "struct " );
208        }
209
210        void CodeGenerator::visit( UnionDecl * unionDecl ) {
211                extension( unionDecl );
212                handleAggregate( unionDecl, "union " );
213        }
214
215        void CodeGenerator::visit( EnumDecl * enumDecl ) {
216                extension( enumDecl );
217                output << "enum ";
218                genAttributes( enumDecl->get_attributes() );
219
220                if ( enumDecl->get_name() != "" )
221                        output << enumDecl->get_name();
222
223                std::list< Declaration* > &memb = enumDecl->get_members();
224
225                if ( ! memb.empty() ) {
226                        output << " {" << endl;
227
228                        cur_indent += CodeGenerator::tabsize;
229                        for ( std::list< Declaration* >::iterator i = memb.begin(); i != memb.end();  i++) {
230                                ObjectDecl * obj = dynamic_cast< ObjectDecl* >( *i );
231                                assert( obj );
232                                output << indent << mangleName( obj );
233                                if ( obj->get_init() ) {
234                                        output << " = ";
235                                        obj->get_init()->accept( *this );
236                                } // if
237                                output << "," << endl;
238                        } // for
239
240                        cur_indent -= CodeGenerator::tabsize;
241
242                        output << indent << "}";
243                } // if
244        }
245
246        void CodeGenerator::visit( TraitDecl * traitDecl ) {}
247
248        void CodeGenerator::visit( TypedefDecl * typeDecl ) {
249                assertf( ! genC, "Typedefs are removed and substituted in earlier passes." );
250                output << "typedef ";
251                output << genType( typeDecl->get_base(), typeDecl->get_name(), pretty, genC ) << endl;
252        }
253
254        void CodeGenerator::visit( TypeDecl * typeDecl ) {
255                if ( genC ) {
256                        // really, we should mutate this into something that isn't a TypeDecl but that requires large-scale changes,
257                        // still to be done
258                        extension( typeDecl );
259                        output << "extern unsigned long " << typeDecl->get_name();
260                        if ( typeDecl->get_base() ) {
261                                output << " = sizeof( " << genType( typeDecl->get_base(), "", pretty, genC ) << " )";
262                        } // if
263                } else {
264                        output << typeDecl->typeString() << " " << typeDecl->get_name();
265                        if ( ! typeDecl->get_assertions().empty() ) {
266                                output << " | { ";
267                                genCommaList( typeDecl->get_assertions().begin(), typeDecl->get_assertions().end() );
268                                output << " }";
269                        }
270                }
271        }
272
273        void CodeGenerator::printDesignators( std::list< Expression * > & designators ) {
274                typedef std::list< Expression * > DesignatorList;
275                if ( designators.size() == 0 ) return;
276                for ( DesignatorList::iterator iter = designators.begin(); iter != designators.end(); ++iter ) {
277                        if ( dynamic_cast< NameExpr * >( *iter ) ) {
278                                // if expression is a name, then initializing aggregate member
279                                output << ".";
280                                (*iter)->accept( *this );
281                        } else {
282                                // if not a simple name, it has to be a constant expression, i.e. an array designator
283                                output << "[";
284                                (*iter)->accept( *this );
285                                output << "]";
286                        } // if
287                } // for
288                output << " = ";
289        }
290
291        void CodeGenerator::visit( SingleInit * init ) {
292                printDesignators( init->get_designators() );
293                init->get_value()->accept( *this );
294        }
295
296        void CodeGenerator::visit( ListInit * init ) {
297                printDesignators( init->get_designators() );
298                output << "{ ";
299                if ( init->begin() == init->end() ) {
300                        // illegal to leave initializer list empty for scalar initializers, but always legal to have 0
301                        output << "0";
302                } else {
303                        genCommaList( init->begin(), init->end() );
304                } // if
305                output << " }";
306        }
307
308        void CodeGenerator::visit( ConstructorInit * init ){
309                assertf( ! genC, "ConstructorInit nodes should not reach code generation." );
310                // xxx - generate something reasonable for constructor/destructor pairs
311                output << "<ctorinit>";
312        }
313
314        void CodeGenerator::visit( Constant * constant ) {
315                output << constant->get_value() ;
316        }
317
318        //*** Expressions
319        void CodeGenerator::visit( ApplicationExpr * applicationExpr ) {
320                extension( applicationExpr );
321                if ( VariableExpr * varExpr = dynamic_cast< VariableExpr* >( applicationExpr->get_function() ) ) {
322                        OperatorInfo opInfo;
323                        if ( varExpr->get_var()->get_linkage() == LinkageSpec::Intrinsic && operatorLookup( varExpr->get_var()->get_name(), opInfo ) ) {
324                                std::list< Expression* >::iterator arg = applicationExpr->get_args().begin();
325                                switch ( opInfo.type ) {
326                                  case OT_PREFIXASSIGN:
327                                  case OT_POSTFIXASSIGN:
328                                  case OT_INFIXASSIGN:
329                                  case OT_CTOR:
330                                  case OT_DTOR:
331                                        {
332                                                assert( arg != applicationExpr->get_args().end() );
333                                                if ( AddressExpr * addrExpr = dynamic_cast< AddressExpr * >( *arg ) ) {
334                                                        // remove & from first assignment/ctor argument
335                                                        *arg = addrExpr->get_arg();
336                                                } else {
337                                                        // no address-of operator, so must be a pointer - add dereference
338                                                        // NOTE: if the assertion starts to trigger, check that the application expr isn't being shared.
339                                                        // Since its arguments are modified here, this assertion most commonly triggers when the application
340                                                        // is visited multiple times.
341                                                        UntypedExpr * newExpr = new UntypedExpr( new NameExpr( "*?" ) );
342                                                        newExpr->get_args().push_back( *arg );
343                                                        Type * type = InitTweak::getPointerBase( (*arg)->get_result() );
344                                                        assertf( type, "First argument to a derefence must be a pointer. Ensure that expressions are not being shared." );
345                                                        newExpr->set_result( type->clone() );
346                                                        *arg = newExpr;
347                                                } // if
348                                                break;
349                                        }
350
351                                  default:
352                                        // do nothing
353                                        ;
354                                } // switch
355
356                                switch ( opInfo.type ) {
357                                  case OT_INDEX:
358                                        assert( applicationExpr->get_args().size() == 2 );
359                                        (*arg++)->accept( *this );
360                                        output << "[";
361                                        (*arg)->accept( *this );
362                                        output << "]";
363                                        break;
364
365                                  case OT_CALL:
366                                        // there are no intrinsic definitions of the function call operator
367                                        assert( false );
368                                        break;
369
370                                  case OT_CTOR:
371                                  case OT_DTOR:
372                                        if ( applicationExpr->get_args().size() == 1 ) {
373                                                // the expression fed into a single parameter constructor or destructor may contain side
374                                                // effects, so must still output this expression
375                                                output << "(";
376                                                (*arg++)->accept( *this );
377                                                output << ") /* " << opInfo.inputName << " */";
378                                        } else if ( applicationExpr->get_args().size() == 2 ) {
379                                                // intrinsic two parameter constructors are essentially bitwise assignment
380                                                output << "(";
381                                                (*arg++)->accept( *this );
382                                                output << opInfo.symbol;
383                                                (*arg)->accept( *this );
384                                                output << ") /* " << opInfo.inputName << " */";
385                                        } else {
386                                                // no constructors with 0 or more than 2 parameters
387                                                assert( false );
388                                        } // if
389                                        break;
390
391                                  case OT_PREFIX:
392                                  case OT_PREFIXASSIGN:
393                                        assert( applicationExpr->get_args().size() == 1 );
394                                        output << "(";
395                                        output << opInfo.symbol;
396                                        (*arg)->accept( *this );
397                                        output << ")";
398                                        break;
399
400                                  case OT_POSTFIX:
401                                  case OT_POSTFIXASSIGN:
402                                        assert( applicationExpr->get_args().size() == 1 );
403                                        (*arg)->accept( *this );
404                                        output << opInfo.symbol;
405                                        break;
406
407
408                                  case OT_INFIX:
409                                  case OT_INFIXASSIGN:
410                                        assert( applicationExpr->get_args().size() == 2 );
411                                        output << "(";
412                                        (*arg++)->accept( *this );
413                                        output << opInfo.symbol;
414                                        (*arg)->accept( *this );
415                                        output << ")";
416                                        break;
417
418                                  case OT_CONSTANT:
419                                  case OT_LABELADDRESS:
420                                        // there are no intrinsic definitions of 0/1 or label addresses as functions
421                                        assert( false );
422                                } // switch
423                        } else {
424                                varExpr->accept( *this );
425                                output << "(";
426                                genCommaList( applicationExpr->get_args().begin(), applicationExpr->get_args().end() );
427                                output << ")";
428                        } // if
429                } else {
430                        applicationExpr->get_function()->accept( *this );
431                        output << "(";
432                        genCommaList( applicationExpr->get_args().begin(), applicationExpr->get_args().end() );
433                        output << ")";
434                } // if
435        }
436
437        void CodeGenerator::visit( UntypedExpr * untypedExpr ) {
438                extension( untypedExpr );
439                if ( NameExpr * nameExpr = dynamic_cast< NameExpr* >( untypedExpr->get_function() ) ) {
440                        OperatorInfo opInfo;
441                        if ( operatorLookup( nameExpr->get_name(), opInfo ) ) {
442                                std::list< Expression* >::iterator arg = untypedExpr->get_args().begin();
443                                switch ( opInfo.type ) {
444                                  case OT_INDEX:
445                                        assert( untypedExpr->get_args().size() == 2 );
446                                        (*arg++)->accept( *this );
447                                        output << "[";
448                                        (*arg)->accept( *this );
449                                        output << "]";
450                                        break;
451
452                                  case OT_CALL:
453                                        assert( false );
454
455                                  case OT_CTOR:
456                                  case OT_DTOR:
457                                        if ( untypedExpr->get_args().size() == 1 ) {
458                                                // the expression fed into a single parameter constructor or destructor may contain side
459                                                // effects, so must still output this expression
460                                                output << "(";
461                                                (*arg++)->accept( *this );
462                                                output << ") /* " << opInfo.inputName << " */";
463                                        } else if ( untypedExpr->get_args().size() == 2 ) {
464                                                // intrinsic two parameter constructors are essentially bitwise assignment
465                                                output << "(";
466                                                (*arg++)->accept( *this );
467                                                output << opInfo.symbol;
468                                                (*arg)->accept( *this );
469                                                output << ") /* " << opInfo.inputName << " */";
470                                        } else {
471                                                // no constructors with 0 or more than 2 parameters
472                                                assert( false );
473                                        } // if
474                                        break;
475
476                                  case OT_PREFIX:
477                                  case OT_PREFIXASSIGN:
478                                  case OT_LABELADDRESS:
479                                        assert( untypedExpr->get_args().size() == 1 );
480                                        output << "(";
481                                        output << opInfo.symbol;
482                                        (*arg)->accept( *this );
483                                        output << ")";
484                                        break;
485
486                                  case OT_POSTFIX:
487                                  case OT_POSTFIXASSIGN:
488                                        assert( untypedExpr->get_args().size() == 1 );
489                                        (*arg)->accept( *this );
490                                        output << opInfo.symbol;
491                                        break;
492
493                                  case OT_INFIX:
494                                  case OT_INFIXASSIGN:
495                                        assert( untypedExpr->get_args().size() == 2 );
496                                        output << "(";
497                                        (*arg++)->accept( *this );
498                                        output << opInfo.symbol;
499                                        (*arg)->accept( *this );
500                                        output << ")";
501                                        break;
502
503                                  case OT_CONSTANT:
504                                        // there are no intrinsic definitions of 0 or 1 as functions
505                                        assert( false );
506                                } // switch
507                        } else {
508                                if ( nameExpr->get_name() == "..." ) { // case V1 ... V2 or case V1~V2
509                                        assert( untypedExpr->get_args().size() == 2 );
510                                        (*untypedExpr->get_args().begin())->accept( *this );
511                                        output << " ... ";
512                                        (*--untypedExpr->get_args().end())->accept( *this );
513                                } else {                                                                // builtin routines
514                                        nameExpr->accept( *this );
515                                        output << "(";
516                                        genCommaList( untypedExpr->get_args().begin(), untypedExpr->get_args().end() );
517                                        output << ")";
518                                } // if
519                        } // if
520                } else {
521                        untypedExpr->get_function()->accept( *this );
522                        output << "(";
523                        genCommaList( untypedExpr->get_args().begin(), untypedExpr->get_args().end() );
524                        output << ")";
525                } // if
526        }
527
528        void CodeGenerator::visit( RangeExpr * rangeExpr ) {
529                rangeExpr->get_low()->accept( *this );
530                output << " ... ";
531                rangeExpr->get_high()->accept( *this );
532        }
533
534        void CodeGenerator::visit( NameExpr * nameExpr ) {
535                extension( nameExpr );
536                OperatorInfo opInfo;
537                if ( operatorLookup( nameExpr->get_name(), opInfo ) ) {
538                        assert( opInfo.type == OT_CONSTANT );
539                        output << opInfo.symbol;
540                } else {
541                        output << nameExpr->get_name();
542                } // if
543        }
544
545        void CodeGenerator::visit( AddressExpr * addressExpr ) {
546                extension( addressExpr );
547                output << "(&";
548                // this hack makes sure that we don't convert "constant_zero" to "0" if we're taking its address
549                if ( VariableExpr * variableExpr = dynamic_cast< VariableExpr* >( addressExpr->get_arg() ) ) {
550                        output << mangleName( variableExpr->get_var() );
551                } else {
552                        addressExpr->get_arg()->accept( *this );
553                } // if
554                output << ")";
555        }
556
557        void CodeGenerator::visit( CastExpr * castExpr ) {
558                extension( castExpr );
559                output << "(";
560                if ( castExpr->get_result()->isVoid() ) {
561                        output << "(void)" ;
562                } else if ( ! castExpr->get_result()->get_lvalue() ) {
563                        // at least one result type of cast, but not an lvalue
564                        output << "(";
565                        output << genType( castExpr->get_result(), "", pretty, genC );
566                        output << ")";
567                } else {
568                        // otherwise, the cast is to an lvalue type, so the cast should be dropped, since the result of a cast is
569                        // never an lvalue in C
570                } // if
571                castExpr->get_arg()->accept( *this );
572                output << ")";
573        }
574
575        void CodeGenerator::visit( UntypedMemberExpr * memberExpr ) {
576                assertf( ! genC, "UntypedMemberExpr should not reach code generation." );
577                extension( memberExpr );
578                memberExpr->get_aggregate()->accept( *this );
579                output << ".";
580                memberExpr->get_member()->accept( *this );
581        }
582
583        void CodeGenerator::visit( MemberExpr * memberExpr ) {
584                extension( memberExpr );
585                memberExpr->get_aggregate()->accept( *this );
586                output << "." << mangleName( memberExpr->get_member() );
587        }
588
589        void CodeGenerator::visit( VariableExpr * variableExpr ) {
590                extension( variableExpr );
591                OperatorInfo opInfo;
592                if ( variableExpr->get_var()->get_linkage() == LinkageSpec::Intrinsic && operatorLookup( variableExpr->get_var()->get_name(), opInfo ) && opInfo.type == OT_CONSTANT ) {
593                        output << opInfo.symbol;
594                } else {
595                        output << mangleName( variableExpr->get_var() );
596                } // if
597        }
598
599        void CodeGenerator::visit( ConstantExpr * constantExpr ) {
600                assert( constantExpr->get_constant() );
601                extension( constantExpr );
602                constantExpr->get_constant()->accept( *this );
603        }
604
605        void CodeGenerator::visit( SizeofExpr * sizeofExpr ) {
606                extension( sizeofExpr );
607                output << "sizeof(";
608                if ( sizeofExpr->get_isType() ) {
609                        output << genType( sizeofExpr->get_type(), "", pretty, genC );
610                } else {
611                        sizeofExpr->get_expr()->accept( *this );
612                } // if
613                output << ")";
614        }
615
616        void CodeGenerator::visit( AlignofExpr * alignofExpr ) {
617                // use GCC extension to avoid bumping std to C11
618                extension( alignofExpr );
619                output << "__alignof__(";
620                if ( alignofExpr->get_isType() ) {
621                        output << genType( alignofExpr->get_type(), "", pretty, genC );
622                } else {
623                        alignofExpr->get_expr()->accept( *this );
624                } // if
625                output << ")";
626        }
627
628        void CodeGenerator::visit( UntypedOffsetofExpr * offsetofExpr ) {
629                assertf( ! genC, "UntypedOffsetofExpr should not reach code generation." );
630                output << "offsetof(";
631                output << genType( offsetofExpr->get_type(), "", pretty, genC );
632                output << ", " << offsetofExpr->get_member();
633                output << ")";
634        }
635
636        void CodeGenerator::visit( OffsetofExpr * offsetofExpr ) {
637                // use GCC builtin
638                output << "__builtin_offsetof(";
639                output << genType( offsetofExpr->get_type(), "", pretty, genC );
640                output << ", " << mangleName( offsetofExpr->get_member() );
641                output << ")";
642        }
643
644        void CodeGenerator::visit( OffsetPackExpr * offsetPackExpr ) {
645                assertf( ! genC, "OffsetPackExpr should not reach code generation." );
646                output << "__CFA_offsetpack(" << genType( offsetPackExpr->get_type(), "", pretty, genC ) << ")";
647        }
648
649        void CodeGenerator::visit( LogicalExpr * logicalExpr ) {
650                extension( logicalExpr );
651                output << "(";
652                logicalExpr->get_arg1()->accept( *this );
653                if ( logicalExpr->get_isAnd() ) {
654                        output << " && ";
655                } else {
656                        output << " || ";
657                } // if
658                logicalExpr->get_arg2()->accept( *this );
659                output << ")";
660        }
661
662        void CodeGenerator::visit( ConditionalExpr * conditionalExpr ) {
663                extension( conditionalExpr );
664                output << "(";
665                conditionalExpr->get_arg1()->accept( *this );
666                output << " ? ";
667                conditionalExpr->get_arg2()->accept( *this );
668                output << " : ";
669                conditionalExpr->get_arg3()->accept( *this );
670                output << ")";
671        }
672
673        void CodeGenerator::visit( CommaExpr * commaExpr ) {
674                extension( commaExpr );
675                output << "(";
676                commaExpr->get_arg1()->accept( *this );
677                output << " , ";
678                commaExpr->get_arg2()->accept( *this );
679                output << ")";
680        }
681
682        void CodeGenerator::visit( UntypedTupleExpr * tupleExpr ) {
683                assertf( ! genC, "UntypedTupleExpr should not reach code generation." );
684                output << "[";
685                genCommaList( tupleExpr->get_exprs().begin(), tupleExpr->get_exprs().end() );
686                output << "]";
687        }
688
689        void CodeGenerator::visit( TupleExpr * tupleExpr ) {
690                assertf( ! genC, "TupleExpr should not reach code generation." );
691                output << "[";
692                genCommaList( tupleExpr->get_exprs().begin(), tupleExpr->get_exprs().end() );
693                output << "]";
694        }
695
696        void CodeGenerator::visit( TypeExpr * typeExpr ) {
697                assertf( ! genC, "TypeExpr should not reach code generation." );
698                output<< genType( typeExpr->get_type(), "", pretty, genC );
699        }
700
701        void CodeGenerator::visit( AsmExpr * asmExpr ) {
702                if ( asmExpr->get_inout() ) {
703                        output << "[ ";
704                        asmExpr->get_inout()->accept( *this );
705                        output << " ] ";
706                } // if
707                asmExpr->get_constraint()->accept( *this );
708                output << " ( ";
709                asmExpr->get_operand()->accept( *this );
710                output << " )";
711        }
712
713        void CodeGenerator::visit( CompoundLiteralExpr *compLitExpr ) {
714                assert( compLitExpr->get_result() && dynamic_cast< ListInit * > ( compLitExpr->get_initializer() ) );
715                output << "(" << genType( compLitExpr->get_result(), "", pretty, genC ) << ")";
716                compLitExpr->get_initializer()->accept( *this );
717        }
718
719        void CodeGenerator::visit( StmtExpr * stmtExpr ) {
720                std::list< Statement * > & stmts = stmtExpr->get_statements()->get_kids();
721                output << "({" << std::endl;
722                cur_indent += CodeGenerator::tabsize;
723                unsigned int numStmts = stmts.size();
724                unsigned int i = 0;
725                for ( Statement * stmt : stmts ) {
726                        output << indent << printLabels( stmt->get_labels() );
727                        if ( i+1 == numStmts ) {
728                                // last statement in a statement expression needs to be handled specially -
729                                // cannot cast to void, otherwise the expression statement has no value
730                                if ( ExprStmt * exprStmt = dynamic_cast< ExprStmt * >( stmt ) ) {
731                                        exprStmt->get_expr()->accept( *this );
732                                        output << ";" << endl;
733                                        ++i;
734                                        break;
735                                }
736                        }
737                        stmt->accept( *this );
738                        output << endl;
739                        if ( wantSpacing( stmt ) ) {
740                                output << endl;
741                        } // if
742                        ++i;
743                }
744                cur_indent -= CodeGenerator::tabsize;
745                output << indent << "})";
746        }
747
748        //*** Statements
749        void CodeGenerator::visit( CompoundStmt * compoundStmt ) {
750                std::list<Statement*> ks = compoundStmt->get_kids();
751                output << "{" << endl;
752
753                cur_indent += CodeGenerator::tabsize;
754
755                for ( std::list<Statement *>::iterator i = ks.begin(); i != ks.end();  i++ ) {
756                        output << indent << printLabels( (*i)->get_labels() );
757                        (*i)->accept( *this );
758
759                        output << endl;
760                        if ( wantSpacing( *i ) ) {
761                                output << endl;
762                        } // if
763                } // for
764                cur_indent -= CodeGenerator::tabsize;
765
766                output << indent << "}";
767        }
768
769        void CodeGenerator::visit( ExprStmt * exprStmt ) {
770                assert( exprStmt );
771                // cast the top-level expression to void to reduce gcc warnings.
772                Expression * expr = new CastExpr( exprStmt->get_expr() );
773                expr->accept( *this );
774                output << ";";
775        }
776
777        void CodeGenerator::visit( AsmStmt * asmStmt ) {
778                output << "asm ";
779                if ( asmStmt->get_voltile() ) output << "volatile ";
780                if ( ! asmStmt->get_gotolabels().empty()  ) output << "goto ";
781                output << "( ";
782                if ( asmStmt->get_instruction() ) asmStmt->get_instruction()->accept( *this );
783                output << " : ";
784                genCommaList( asmStmt->get_output().begin(), asmStmt->get_output().end() );
785                output << " : ";
786                genCommaList( asmStmt->get_input().begin(), asmStmt->get_input().end() );
787                output << " : ";
788                genCommaList( asmStmt->get_clobber().begin(), asmStmt->get_clobber().end() );
789                if ( ! asmStmt->get_gotolabels().empty() ) {
790                        output << " : ";
791                        for ( std::list<Label>::iterator begin = asmStmt->get_gotolabels().begin();; ) {
792                                output << *begin++;
793                                if ( begin == asmStmt->get_gotolabels().end() ) break;
794                                output << ", ";
795                        } // for
796                } // if
797                output << " );" ;
798        }
799
800        void CodeGenerator::visit( AsmDecl * asmDecl ) {
801                output << "asm ";
802                AsmStmt * asmStmt = asmDecl->get_stmt();
803                output << "( ";
804                if ( asmStmt->get_instruction() ) asmStmt->get_instruction()->accept( *this );
805                output << " )" ;
806        }
807
808        void CodeGenerator::visit( IfStmt * ifStmt ) {
809                output << "if ( ";
810                ifStmt->get_condition()->accept( *this );
811                output << " ) ";
812
813                ifStmt->get_thenPart()->accept( *this );
814
815                if ( ifStmt->get_elsePart() != 0) {
816                        output << " else ";
817                        ifStmt->get_elsePart()->accept( *this );
818                } // if
819        }
820
821        void CodeGenerator::visit( SwitchStmt * switchStmt ) {
822                output << "switch ( " ;
823                switchStmt->get_condition()->accept( *this );
824                output << " ) ";
825
826                output << "{" << std::endl;
827                cur_indent += CodeGenerator::tabsize;
828                acceptAll( switchStmt->get_statements(), *this );
829                cur_indent -= CodeGenerator::tabsize;
830                output << indent << "}";
831        }
832
833        void CodeGenerator::visit( CaseStmt * caseStmt ) {
834                output << indent;
835                if ( caseStmt->isDefault()) {
836                        output << "default";
837                } else {
838                        output << "case ";
839                        caseStmt->get_condition()->accept( *this );
840                } // if
841                output << ":\n";
842
843                std::list<Statement *> sts = caseStmt->get_statements();
844
845                cur_indent += CodeGenerator::tabsize;
846                for ( std::list<Statement *>::iterator i = sts.begin(); i != sts.end();  i++) {
847                        output << indent << printLabels( (*i)->get_labels() )  ;
848                        (*i)->accept( *this );
849                        output << endl;
850                } // for
851                cur_indent -= CodeGenerator::tabsize;
852        }
853
854        void CodeGenerator::visit( BranchStmt * branchStmt ) {
855                switch ( branchStmt->get_type()) {
856                  case BranchStmt::Goto:
857                        if ( ! branchStmt->get_target().empty() )
858                                output << "goto " << branchStmt->get_target();
859                        else {
860                                if ( branchStmt->get_computedTarget() != 0 ) {
861                                        output << "goto *";
862                                        branchStmt->get_computedTarget()->accept( *this );
863                                } // if
864                        } // if
865                        break;
866                  case BranchStmt::Break:
867                        output << "break";
868                        break;
869                  case BranchStmt::Continue:
870                        output << "continue";
871                        break;
872                } // switch
873                output << ";";
874        }
875
876        void CodeGenerator::visit( ReturnStmt * returnStmt ) {
877                output << "return ";
878                maybeAccept( returnStmt->get_expr(), *this );
879                output << ";";
880        }
881
882        void CodeGenerator::visit( WhileStmt * whileStmt ) {
883                if ( whileStmt->get_isDoWhile() ) {
884                        output << "do" ;
885                } else {
886                        output << "while (" ;
887                        whileStmt->get_condition()->accept( *this );
888                        output << ")";
889                } // if
890                output << " ";
891
892                output << CodeGenerator::printLabels( whileStmt->get_body()->get_labels() );
893                whileStmt->get_body()->accept( *this );
894
895                output << indent;
896
897                if ( whileStmt->get_isDoWhile() ) {
898                        output << " while (" ;
899                        whileStmt->get_condition()->accept( *this );
900                        output << ");";
901                } // if
902        }
903
904        void CodeGenerator::visit( ForStmt * forStmt ) {
905                // initialization is always hoisted, so don't bother doing anything with that
906                output << "for (;";
907
908                if ( forStmt->get_condition() != 0 ) {
909                        forStmt->get_condition()->accept( *this );
910                } // if
911                output << ";";
912
913                if ( forStmt->get_increment() != 0 ) {
914                        // cast the top-level expression to void to reduce gcc warnings.
915                        Expression * expr = new CastExpr( forStmt->get_increment() );
916                        expr->accept( *this );
917                } // if
918                output << ") ";
919
920                if ( forStmt->get_body() != 0 ) {
921                        output << CodeGenerator::printLabels( forStmt->get_body()->get_labels() );
922                        forStmt->get_body()->accept( *this );
923                } // if
924        }
925
926        void CodeGenerator::visit( NullStmt * nullStmt ) {
927                //output << indent << CodeGenerator::printLabels( nullStmt->get_labels() );
928                output << "/* null statement */ ;";
929        }
930
931        void CodeGenerator::visit( DeclStmt * declStmt ) {
932                declStmt->get_decl()->accept( *this );
933
934                if ( doSemicolon( declStmt->get_decl() ) ) {
935                        output << ";";
936                } // if
937        }
938
939        void CodeGenerator::handleStorageClass( DeclarationWithType * decl ) {
940                if ( decl->get_storageClasses().any() ) {
941                        decl->get_storageClasses().print( output );
942                } // if
943        } // CodeGenerator::handleStorageClass
944
945        std::string genName( DeclarationWithType * decl ) {
946                CodeGen::OperatorInfo opInfo;
947                if ( operatorLookup( decl->get_name(), opInfo ) ) {
948                        return opInfo.outputName;
949                } else {
950                        return decl->get_name();
951                } // if
952        }
953} // namespace CodeGen
954
955// Local Variables: //
956// tab-width: 4 //
957// mode: c++ //
958// compile-command: "make install" //
959// End: //
Note: See TracBrowser for help on using the repository browser.