source: src/CodeGen/CodeGenerator.cc @ 7ebaa56

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

Merge branch 'master' into references

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