source: src/CodeGen/CodeGenerator.cc @ 9ebd778

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 9ebd778 was f975c65, checked in by Rob Schluntz <rschlunt@…>, 7 years ago

intermediate codegen for tuple indexing

  • Property mode set to 100644
File size: 30.5 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                extension( tupleExpr );
712                output << "[";
713                genCommaList( tupleExpr->get_exprs().begin(), tupleExpr->get_exprs().end() );
714                output << "]";
715        }
716
717        void CodeGenerator::visit( TupleExpr * tupleExpr ) {
718                assertf( ! genC, "TupleExpr should not reach code generation." );
719                extension( tupleExpr );
720                output << "[";
721                genCommaList( tupleExpr->get_exprs().begin(), tupleExpr->get_exprs().end() );
722                output << "]";
723        }
724
725        void CodeGenerator::visit( TupleIndexExpr * tupleExpr ) {
726                assertf( ! genC, "TupleIndexExpr should not reach code generation." );
727                extension( tupleExpr );
728                tupleExpr->get_tuple()->accept( *this );
729                output << "." << tupleExpr->get_index();
730        }
731
732        void CodeGenerator::visit( TypeExpr * typeExpr ) {
733                assertf( ! genC, "TypeExpr should not reach code generation." );
734                output<< genType( typeExpr->get_type(), "", pretty, genC );
735        }
736
737        void CodeGenerator::visit( AsmExpr * asmExpr ) {
738                if ( asmExpr->get_inout() ) {
739                        output << "[ ";
740                        asmExpr->get_inout()->accept( *this );
741                        output << " ] ";
742                } // if
743                asmExpr->get_constraint()->accept( *this );
744                output << " ( ";
745                asmExpr->get_operand()->accept( *this );
746                output << " )";
747        }
748
749        void CodeGenerator::visit( CompoundLiteralExpr *compLitExpr ) {
750                assert( compLitExpr->get_result() && dynamic_cast< ListInit * > ( compLitExpr->get_initializer() ) );
751                output << "(" << genType( compLitExpr->get_result(), "", pretty, genC ) << ")";
752                compLitExpr->get_initializer()->accept( *this );
753        }
754
755        void CodeGenerator::visit( StmtExpr * stmtExpr ) {
756                std::list< Statement * > & stmts = stmtExpr->get_statements()->get_kids();
757                output << lineDirective( stmtExpr) << "({" << std::endl;
758                cur_indent += CodeGenerator::tabsize;
759                unsigned int numStmts = stmts.size();
760                unsigned int i = 0;
761                for ( Statement * stmt : stmts ) {
762                        output << lineDirective( stmt ) << indent;
763            output << printLabels( stmt->get_labels() );
764                        if ( i+1 == numStmts ) {
765                                // last statement in a statement expression needs to be handled specially -
766                                // cannot cast to void, otherwise the expression statement has no value
767                                if ( ExprStmt * exprStmt = dynamic_cast< ExprStmt * >( stmt ) ) {
768                                        exprStmt->get_expr()->accept( *this );
769                                        output << ";" << endl;
770                                        ++i;
771                                        break;
772                                }
773                        }
774                        stmt->accept( *this );
775                        output << endl;
776                        if ( wantSpacing( stmt ) ) {
777                                output << endl;
778                        } // if
779                        ++i;
780                }
781                cur_indent -= CodeGenerator::tabsize;
782                output << indent << "})";
783        }
784
785        // *** Statements
786        void CodeGenerator::visit( CompoundStmt * compoundStmt ) {
787                std::list<Statement*> ks = compoundStmt->get_kids();
788                output << "{" << endl;
789
790                cur_indent += CodeGenerator::tabsize;
791
792                for ( std::list<Statement *>::iterator i = ks.begin(); i != ks.end();  i++ ) {
793                        output << indent << printLabels( (*i)->get_labels() );
794                        (*i)->accept( *this );
795
796                        output << endl;
797                        if ( wantSpacing( *i ) ) {
798                                output << endl;
799                        } // if
800                } // for
801                cur_indent -= CodeGenerator::tabsize;
802
803                output << indent << "}";
804        }
805
806        void CodeGenerator::visit( ExprStmt * exprStmt ) {
807                assert( exprStmt );
808                Expression * expr = exprStmt->get_expr();
809                if ( genC ) {
810                        // cast the top-level expression to void to reduce gcc warnings.
811                        expr = new CastExpr( expr );
812                }
813                expr->accept( *this );
814                output << ";";
815        }
816
817        void CodeGenerator::visit( AsmStmt * asmStmt ) {
818                output << "asm ";
819                if ( asmStmt->get_voltile() ) output << "volatile ";
820                if ( ! asmStmt->get_gotolabels().empty()  ) output << "goto ";
821                output << "( ";
822                if ( asmStmt->get_instruction() ) asmStmt->get_instruction()->accept( *this );
823                output << " : ";
824                genCommaList( asmStmt->get_output().begin(), asmStmt->get_output().end() );
825                output << " : ";
826                genCommaList( asmStmt->get_input().begin(), asmStmt->get_input().end() );
827                output << " : ";
828                genCommaList( asmStmt->get_clobber().begin(), asmStmt->get_clobber().end() );
829                if ( ! asmStmt->get_gotolabels().empty() ) {
830                        output << " : ";
831                        for ( std::list<Label>::iterator begin = asmStmt->get_gotolabels().begin();; ) {
832                                output << *begin++;
833                                if ( begin == asmStmt->get_gotolabels().end() ) break;
834                                output << ", ";
835                        } // for
836                } // if
837                output << " );" ;
838        }
839
840        void CodeGenerator::visit( AsmDecl * asmDecl ) {
841                output << "asm ";
842                AsmStmt * asmStmt = asmDecl->get_stmt();
843                output << "( ";
844                if ( asmStmt->get_instruction() ) asmStmt->get_instruction()->accept( *this );
845                output << " )" ;
846        }
847
848        void CodeGenerator::visit( IfStmt * ifStmt ) {
849                output << lineDirective( ifStmt );
850                output << "if ( ";
851                ifStmt->get_condition()->accept( *this );
852                output << " ) ";
853
854                ifStmt->get_thenPart()->accept( *this );
855
856                if ( ifStmt->get_elsePart() != 0) {
857                        output << " else ";
858                        ifStmt->get_elsePart()->accept( *this );
859                } // if
860        }
861
862        void CodeGenerator::visit( SwitchStmt * switchStmt ) {
863                output << lineDirective( switchStmt );
864                output << "switch ( " ;
865                switchStmt->get_condition()->accept( *this );
866                output << " ) ";
867
868                output << "{" << std::endl;
869                cur_indent += CodeGenerator::tabsize;
870                acceptAll( switchStmt->get_statements(), *this );
871                cur_indent -= CodeGenerator::tabsize;
872                output << indent << "}";
873        }
874
875        void CodeGenerator::visit( CaseStmt * caseStmt ) {
876                output << lineDirective( caseStmt );
877                output << indent;
878                if ( caseStmt->isDefault()) {
879                        output << "default";
880                } else {
881                        output << "case ";
882                        caseStmt->get_condition()->accept( *this );
883                } // if
884                output << ":\n";
885
886                std::list<Statement *> sts = caseStmt->get_statements();
887
888                cur_indent += CodeGenerator::tabsize;
889                for ( std::list<Statement *>::iterator i = sts.begin(); i != sts.end();  i++) {
890                        output << indent << printLabels( (*i)->get_labels() )  ;
891                        (*i)->accept( *this );
892                        output << endl;
893                } // for
894                cur_indent -= CodeGenerator::tabsize;
895        }
896
897        void CodeGenerator::visit( BranchStmt * branchStmt ) {
898                switch ( branchStmt->get_type()) {
899                  case BranchStmt::Goto:
900                        if ( ! branchStmt->get_target().empty() )
901                                output << "goto " << branchStmt->get_target();
902                        else {
903                                if ( branchStmt->get_computedTarget() != 0 ) {
904                                        output << "goto *";
905                                        branchStmt->get_computedTarget()->accept( *this );
906                                } // if
907                        } // if
908                        break;
909                  case BranchStmt::Break:
910                        output << "break";
911                        break;
912                  case BranchStmt::Continue:
913                        output << "continue";
914                        break;
915                } // switch
916                output << ";";
917        }
918
919        void CodeGenerator::visit( ReturnStmt * returnStmt ) {
920                output << "return ";
921                maybeAccept( returnStmt->get_expr(), *this );
922                output << ";";
923        }
924
925        void CodeGenerator::visit( WhileStmt * whileStmt ) {
926                if ( whileStmt->get_isDoWhile() ) {
927                        output << "do" ;
928                } else {
929                        output << "while (" ;
930                        whileStmt->get_condition()->accept( *this );
931                        output << ")";
932                } // if
933                output << " ";
934
935                output << CodeGenerator::printLabels( whileStmt->get_body()->get_labels() );
936                whileStmt->get_body()->accept( *this );
937
938                output << indent;
939
940                if ( whileStmt->get_isDoWhile() ) {
941                        output << " while (" ;
942                        whileStmt->get_condition()->accept( *this );
943                        output << ");";
944                } // if
945        }
946
947        void CodeGenerator::visit( ForStmt * forStmt ) {
948                // initialization is always hoisted, so don't bother doing anything with that
949                output << "for (;";
950
951                if ( forStmt->get_condition() != 0 ) {
952                        forStmt->get_condition()->accept( *this );
953                } // if
954                output << ";";
955
956                if ( forStmt->get_increment() != 0 ) {
957                        // cast the top-level expression to void to reduce gcc warnings.
958                        Expression * expr = new CastExpr( forStmt->get_increment() );
959                        expr->accept( *this );
960                } // if
961                output << ") ";
962
963                if ( forStmt->get_body() != 0 ) {
964                        output << CodeGenerator::printLabels( forStmt->get_body()->get_labels() );
965                        forStmt->get_body()->accept( *this );
966                } // if
967        }
968
969        void CodeGenerator::visit( NullStmt * nullStmt ) {
970                //output << indent << CodeGenerator::printLabels( nullStmt->get_labels() );
971                output << "/* null statement */ ;";
972        }
973
974        void CodeGenerator::visit( DeclStmt * declStmt ) {
975                declStmt->get_decl()->accept( *this );
976
977                if ( doSemicolon( declStmt->get_decl() ) ) {
978                        output << ";";
979                } // if
980        }
981
982        void CodeGenerator::handleStorageClass( DeclarationWithType * decl ) {
983                if ( decl->get_storageClasses().any() ) {
984                        decl->get_storageClasses().print( output );
985                } // if
986        } // CodeGenerator::handleStorageClass
987
988        std::string genName( DeclarationWithType * decl ) {
989                CodeGen::OperatorInfo opInfo;
990                if ( operatorLookup( decl->get_name(), opInfo ) ) {
991                        return opInfo.outputName;
992                } else {
993                        return decl->get_name();
994                } // if
995        }
996} // namespace CodeGen
997
998// Local Variables: //
999// tab-width: 4 //
1000// mode: c++ //
1001// compile-command: "make install" //
1002// End: //
Note: See TracBrowser for help on using the repository browser.