source: src/CodeGen/CodeGenerator.cc @ c850687

ADTaaron-thesisarm-ehcleanup-dtorsdeferred_resndemanglerenumforall-pointer-decayjacob/cs343-translationjenkins-sandboxnew-astnew-ast-unique-exprnew-envno_listpersistent-indexerpthread-emulationqualifiedEnumresolv-newwith_gc
Last change on this file since c850687 was c850687, checked in by Andrew Beach <ajbeach@…>, 6 years ago

Add -L flag to turn of line marks. Updated the keyword list.

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