source: src/CodeGen/CodeGenerator.cc @ b3f252a

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 b3f252a was e612146c, checked in by Peter A. Buhr <pabuhr@…>, 7 years ago

third attempt at user-defined literals

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