source: src/CodeGen/CodeGenerator.cc @ e4ea10b7

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 e4ea10b7 was e4ea10b7, checked in by Thierry Delisle <tdelisle@…>, 7 years ago

Added codegen code for waitfor and catch stmt

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