source: src/CodeGen/CodeGenerator.cc @ f0ecf9b

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

Remove TypeDecl::Any, as it is subsumed by Dtype+sized

  • Property mode set to 100644
File size: 33.6 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->name;
290                if ( typeDecl->sized ) {
291                        output << " | sized(" << typeDecl->name << ")";
292                }
293                if ( ! typeDecl->assertions.empty() ) {
294                        output << " | { ";
295                        for ( DeclarationWithType * assert :  typeDecl->assertions ) {
296                                assert->accept( *visitor );
297                                output << "; ";
298                        }
299                        output << " }";
300                }
301        }
302
303        void CodeGenerator::postvisit( Designation * designation ) {
304                std::list< Expression * > designators = designation->get_designators();
305                if ( designators.size() == 0 ) return;
306                for ( Expression * des : designators ) {
307                        if ( dynamic_cast< NameExpr * >( des ) || dynamic_cast< VariableExpr * >( des ) ) {
308                                // if expression is a NameExpr or VariableExpr, then initializing aggregate member
309                                output << ".";
310                                des->accept( *visitor );
311                        } else {
312                                // otherwise, it has to be a ConstantExpr or CastExpr, initializing array eleemnt
313                                output << "[";
314                                des->accept( *visitor );
315                                output << "]";
316                        } // if
317                } // for
318                output << " = ";
319        }
320
321        void CodeGenerator::postvisit( SingleInit * init ) {
322                init->get_value()->accept( *visitor );
323        }
324
325        void CodeGenerator::postvisit( ListInit * init ) {
326                auto initBegin = init->begin();
327                auto initEnd = init->end();
328                auto desigBegin = init->get_designations().begin();
329                auto desigEnd = init->get_designations().end();
330
331                output << "{ ";
332                for ( ; initBegin != initEnd && desigBegin != desigEnd; ) {
333                        (*desigBegin)->accept( *visitor );
334                        (*initBegin)->accept( *visitor );
335                        ++initBegin, ++desigBegin;
336                        if ( initBegin != initEnd ) {
337                                output << ", ";
338                        }
339                }
340                output << " }";
341                assertf( initBegin == initEnd && desigBegin == desigEnd, "Initializers and designators not the same length. %s", toString( init ).c_str() );
342        }
343
344        void CodeGenerator::postvisit( ConstructorInit * init ){
345                assertf( ! genC, "ConstructorInit nodes should not reach code generation." );
346                // pseudo-output for constructor/destructor pairs
347                output << "<ctorinit>{" << endl << ++indent << "ctor: ";
348                maybeAccept( init->get_ctor(), *visitor );
349                output << ", " << endl << indent << "dtor: ";
350                maybeAccept( init->get_dtor(), *visitor );
351                output << endl << --indent << "}";
352        }
353
354        void CodeGenerator::postvisit( Constant * constant ) {
355                output << constant->get_value() ;
356        }
357
358        // *** Expressions
359        void CodeGenerator::postvisit( ApplicationExpr * applicationExpr ) {
360                extension( applicationExpr );
361                if ( VariableExpr * varExpr = dynamic_cast< VariableExpr* >( applicationExpr->get_function() ) ) {
362                        OperatorInfo opInfo;
363                        if ( varExpr->get_var()->get_linkage() == LinkageSpec::Intrinsic && operatorLookup( varExpr->get_var()->get_name(), opInfo ) ) {
364                                std::list< Expression* >::iterator arg = applicationExpr->get_args().begin();
365                                switch ( opInfo.type ) {
366                                  case OT_INDEX:
367                                        assert( applicationExpr->get_args().size() == 2 );
368                                        (*arg++)->accept( *visitor );
369                                        output << "[";
370                                        (*arg)->accept( *visitor );
371                                        output << "]";
372                                        break;
373
374                                  case OT_CALL:
375                                        // there are no intrinsic definitions of the function call operator
376                                        assert( false );
377                                        break;
378
379                                  case OT_CTOR:
380                                  case OT_DTOR:
381                                        if ( applicationExpr->get_args().size() == 1 ) {
382                                                // the expression fed into a single parameter constructor or destructor may contain side
383                                                // effects, so must still output this expression
384                                                output << "(";
385                                                (*arg++)->accept( *visitor );
386                                                output << ") /* " << opInfo.inputName << " */";
387                                        } else if ( applicationExpr->get_args().size() == 2 ) {
388                                                // intrinsic two parameter constructors are essentially bitwise assignment
389                                                output << "(";
390                                                (*arg++)->accept( *visitor );
391                                                output << opInfo.symbol;
392                                                (*arg)->accept( *visitor );
393                                                output << ") /* " << opInfo.inputName << " */";
394                                        } else {
395                                                // no constructors with 0 or more than 2 parameters
396                                                assert( false );
397                                        } // if
398                                        break;
399
400                                  case OT_PREFIX:
401                                  case OT_PREFIXASSIGN:
402                                        assert( applicationExpr->get_args().size() == 1 );
403                                        output << "(";
404                                        output << opInfo.symbol;
405                                        (*arg)->accept( *visitor );
406                                        output << ")";
407                                        break;
408
409                                  case OT_POSTFIX:
410                                  case OT_POSTFIXASSIGN:
411                                        assert( applicationExpr->get_args().size() == 1 );
412                                        (*arg)->accept( *visitor );
413                                        output << opInfo.symbol;
414                                        break;
415
416
417                                  case OT_INFIX:
418                                  case OT_INFIXASSIGN:
419                                        assert( applicationExpr->get_args().size() == 2 );
420                                        output << "(";
421                                        (*arg++)->accept( *visitor );
422                                        output << opInfo.symbol;
423                                        (*arg)->accept( *visitor );
424                                        output << ")";
425                                        break;
426
427                                  case OT_CONSTANT:
428                                  case OT_LABELADDRESS:
429                                        // there are no intrinsic definitions of 0/1 or label addresses as functions
430                                        assert( false );
431                                } // switch
432                        } else {
433                                varExpr->accept( *visitor );
434                                output << "(";
435                                genCommaList( applicationExpr->get_args().begin(), applicationExpr->get_args().end() );
436                                output << ")";
437                        } // if
438                } else {
439                        applicationExpr->get_function()->accept( *visitor );
440                        output << "(";
441                        genCommaList( applicationExpr->get_args().begin(), applicationExpr->get_args().end() );
442                        output << ")";
443                } // if
444        }
445
446        void CodeGenerator::postvisit( UntypedExpr * untypedExpr ) {
447                extension( untypedExpr );
448                if ( NameExpr * nameExpr = dynamic_cast< NameExpr* >( untypedExpr->function ) ) {
449                        OperatorInfo opInfo;
450                        if ( operatorLookup( nameExpr->name, opInfo ) ) {
451                                std::list< Expression* >::iterator arg = untypedExpr->args.begin();
452                                switch ( opInfo.type ) {
453                                  case OT_INDEX:
454                                        assert( untypedExpr->args.size() == 2 );
455                                        (*arg++)->accept( *visitor );
456                                        output << "[";
457                                        (*arg)->accept( *visitor );
458                                        output << "]";
459                                        break;
460
461                                  case OT_CALL:
462                                        assert( false );
463
464                                  case OT_CTOR:
465                                  case OT_DTOR:
466                                        if ( untypedExpr->args.size() == 1 ) {
467                                                // the expression fed into a single parameter constructor or destructor may contain side
468                                                // effects, so must still output this expression
469                                                output << "(";
470                                                (*arg++)->accept( *visitor );
471                                                output << ") /* " << opInfo.inputName << " */";
472                                        } else if ( untypedExpr->get_args().size() == 2 ) {
473                                                // intrinsic two parameter constructors are essentially bitwise assignment
474                                                output << "(";
475                                                (*arg++)->accept( *visitor );
476                                                output << opInfo.symbol;
477                                                (*arg)->accept( *visitor );
478                                                output << ") /* " << opInfo.inputName << " */";
479                                        } else {
480                                                // no constructors with 0 or more than 2 parameters
481                                                assertf( ! genC, "UntypedExpr constructor/destructor with 0 or more than 2 parameters." );
482                                                output << "(";
483                                                (*arg++)->accept( *visitor );
484                                                output << opInfo.symbol << "{ ";
485                                                genCommaList( arg, untypedExpr->args.end() );
486                                                output << "}) /* " << opInfo.inputName << " */";
487                                        } // if
488                                        break;
489
490                                  case OT_PREFIX:
491                                  case OT_PREFIXASSIGN:
492                                  case OT_LABELADDRESS:
493                                        assert( untypedExpr->args.size() == 1 );
494                                        output << "(";
495                                        output << opInfo.symbol;
496                                        (*arg)->accept( *visitor );
497                                        output << ")";
498                                        break;
499
500                                  case OT_POSTFIX:
501                                  case OT_POSTFIXASSIGN:
502                                        assert( untypedExpr->args.size() == 1 );
503                                        (*arg)->accept( *visitor );
504                                        output << opInfo.symbol;
505                                        break;
506
507                                  case OT_INFIX:
508                                  case OT_INFIXASSIGN:
509                                        assert( untypedExpr->args.size() == 2 );
510                                        output << "(";
511                                        (*arg++)->accept( *visitor );
512                                        output << opInfo.symbol;
513                                        (*arg)->accept( *visitor );
514                                        output << ")";
515                                        break;
516
517                                  case OT_CONSTANT:
518                                        // there are no intrinsic definitions of 0 or 1 as functions
519                                        assert( false );
520                                } // switch
521                        } else {
522                                // builtin routines
523                                nameExpr->accept( *visitor );
524                                output << "(";
525                                genCommaList( untypedExpr->args.begin(), untypedExpr->args.end() );
526                                output << ")";
527                        } // if
528                } else {
529                        untypedExpr->function->accept( *visitor );
530                        output << "(";
531                        genCommaList( untypedExpr->args.begin(), untypedExpr->args.end() );
532                        output << ")";
533                } // if
534        }
535
536        void CodeGenerator::postvisit( RangeExpr * rangeExpr ) {
537                rangeExpr->low->accept( *visitor );
538                output << " ... ";
539                rangeExpr->high->accept( *visitor );
540        }
541
542        void CodeGenerator::postvisit( NameExpr * nameExpr ) {
543                extension( nameExpr );
544                OperatorInfo opInfo;
545                if ( operatorLookup( nameExpr->name, opInfo ) ) {
546                        if ( opInfo.type == OT_CONSTANT ) {
547                                output << opInfo.symbol;
548                        } else {
549                                output << opInfo.outputName;
550                        }
551                } else {
552                        output << nameExpr->get_name();
553                } // if
554        }
555
556        void CodeGenerator::postvisit( AddressExpr * addressExpr ) {
557                extension( addressExpr );
558                output << "(&";
559                addressExpr->arg->accept( *visitor );
560                output << ")";
561        }
562
563        void CodeGenerator::postvisit( LabelAddressExpr *addressExpr ) {
564                extension( addressExpr );
565                output << "(&&" << addressExpr->arg << ")";
566        }
567
568        void CodeGenerator::postvisit( CastExpr * castExpr ) {
569                extension( castExpr );
570                output << "(";
571                if ( castExpr->get_result()->isVoid() ) {
572                        output << "(void)" ;
573                } else {
574                        // at least one result type of cast.
575                        // Note: previously, lvalue casts were skipped. Since it's now impossible for the user to write
576                        // an lvalue cast, this has been taken out.
577                        output << "(";
578                        output << genType( castExpr->get_result(), "", pretty, genC );
579                        output << ")";
580                } // if
581                castExpr->get_arg()->accept( *visitor );
582                output << ")";
583        }
584
585        void CodeGenerator::postvisit( VirtualCastExpr * castExpr ) {
586                assertf( ! genC, "VirtualCastExpr should not reach code generation." );
587                extension( castExpr );
588                output << "(virtual ";
589                castExpr->get_arg()->accept( *visitor );
590                output << ")";
591        }
592
593        void CodeGenerator::postvisit( UntypedMemberExpr * memberExpr ) {
594                assertf( ! genC, "UntypedMemberExpr should not reach code generation." );
595                extension( memberExpr );
596                memberExpr->get_aggregate()->accept( *visitor );
597                output << ".";
598                memberExpr->get_member()->accept( *visitor );
599        }
600
601        void CodeGenerator::postvisit( MemberExpr * memberExpr ) {
602                extension( memberExpr );
603                memberExpr->get_aggregate()->accept( *visitor );
604                output << "." << mangleName( memberExpr->get_member() );
605        }
606
607        void CodeGenerator::postvisit( VariableExpr * variableExpr ) {
608                extension( variableExpr );
609                OperatorInfo opInfo;
610                if ( variableExpr->get_var()->get_linkage() == LinkageSpec::Intrinsic && operatorLookup( variableExpr->get_var()->get_name(), opInfo ) && opInfo.type == OT_CONSTANT ) {
611                        output << opInfo.symbol;
612                } else {
613                        output << mangleName( variableExpr->get_var() );
614                } // if
615        }
616
617        void CodeGenerator::postvisit( ConstantExpr * constantExpr ) {
618                assert( constantExpr->get_constant() );
619                extension( constantExpr );
620                constantExpr->get_constant()->accept( *visitor );
621        }
622
623        void CodeGenerator::postvisit( SizeofExpr * sizeofExpr ) {
624                extension( sizeofExpr );
625                output << "sizeof(";
626                if ( sizeofExpr->get_isType() ) {
627                        output << genType( sizeofExpr->get_type(), "", pretty, genC );
628                } else {
629                        sizeofExpr->get_expr()->accept( *visitor );
630                } // if
631                output << ")";
632        }
633
634        void CodeGenerator::postvisit( AlignofExpr * alignofExpr ) {
635                // use GCC extension to avoid bumping std to C11
636                extension( alignofExpr );
637                output << "__alignof__(";
638                if ( alignofExpr->get_isType() ) {
639                        output << genType( alignofExpr->get_type(), "", pretty, genC );
640                } else {
641                        alignofExpr->get_expr()->accept( *visitor );
642                } // if
643                output << ")";
644        }
645
646        void CodeGenerator::postvisit( UntypedOffsetofExpr * offsetofExpr ) {
647                assertf( ! genC, "UntypedOffsetofExpr should not reach code generation." );
648                output << "offsetof(";
649                output << genType( offsetofExpr->get_type(), "", pretty, genC );
650                output << ", " << offsetofExpr->get_member();
651                output << ")";
652        }
653
654        void CodeGenerator::postvisit( OffsetofExpr * offsetofExpr ) {
655                // use GCC builtin
656                output << "__builtin_offsetof(";
657                output << genType( offsetofExpr->get_type(), "", pretty, genC );
658                output << ", " << mangleName( offsetofExpr->get_member() );
659                output << ")";
660        }
661
662        void CodeGenerator::postvisit( OffsetPackExpr * offsetPackExpr ) {
663                assertf( ! genC, "OffsetPackExpr should not reach code generation." );
664                output << "__CFA_offsetpack(" << genType( offsetPackExpr->get_type(), "", pretty, genC ) << ")";
665        }
666
667        void CodeGenerator::postvisit( LogicalExpr * logicalExpr ) {
668                extension( logicalExpr );
669                output << "(";
670                logicalExpr->get_arg1()->accept( *visitor );
671                if ( logicalExpr->get_isAnd() ) {
672                        output << " && ";
673                } else {
674                        output << " || ";
675                } // if
676                logicalExpr->get_arg2()->accept( *visitor );
677                output << ")";
678        }
679
680        void CodeGenerator::postvisit( ConditionalExpr * conditionalExpr ) {
681                extension( conditionalExpr );
682                output << "(";
683                conditionalExpr->get_arg1()->accept( *visitor );
684                output << " ? ";
685                conditionalExpr->get_arg2()->accept( *visitor );
686                output << " : ";
687                conditionalExpr->get_arg3()->accept( *visitor );
688                output << ")";
689        }
690
691        void CodeGenerator::postvisit( CommaExpr * commaExpr ) {
692                extension( commaExpr );
693                output << "(";
694                if ( genC ) {
695                        // arg1 of a CommaExpr is never used, so it can be safely cast to void to reduce gcc warnings.
696                        commaExpr->set_arg1( new CastExpr( commaExpr->get_arg1() ) );
697                }
698                commaExpr->get_arg1()->accept( *visitor );
699                output << " , ";
700                commaExpr->get_arg2()->accept( *visitor );
701                output << ")";
702        }
703
704        void CodeGenerator::postvisit( TupleAssignExpr * tupleExpr ) {
705                assertf( ! genC, "TupleAssignExpr should not reach code generation." );
706                tupleExpr->stmtExpr->accept( *visitor );
707        }
708
709        void CodeGenerator::postvisit( UntypedTupleExpr * tupleExpr ) {
710                assertf( ! genC, "UntypedTupleExpr should not reach code generation." );
711                extension( tupleExpr );
712                output << "[";
713                genCommaList( tupleExpr->get_exprs().begin(), tupleExpr->get_exprs().end() );
714                output << "]";
715        }
716
717        void CodeGenerator::postvisit( TupleExpr * tupleExpr ) {
718                assertf( ! genC, "TupleExpr should not reach code generation." );
719                extension( tupleExpr );
720                output << "[";
721                genCommaList( tupleExpr->get_exprs().begin(), tupleExpr->get_exprs().end() );
722                output << "]";
723        }
724
725        void CodeGenerator::postvisit( TupleIndexExpr * tupleExpr ) {
726                assertf( ! genC, "TupleIndexExpr should not reach code generation." );
727                extension( tupleExpr );
728                tupleExpr->get_tuple()->accept( *visitor );
729                output << "." << tupleExpr->get_index();
730        }
731
732        void CodeGenerator::postvisit( TypeExpr * typeExpr ) {
733                // if ( genC ) std::cerr << "typeexpr still exists: " << typeExpr << std::endl;
734                // assertf( ! genC, "TypeExpr should not reach code generation." );
735                if ( ! genC ) {
736                        output<< genType( typeExpr->get_type(), "", pretty, genC );
737                }
738        }
739
740        void CodeGenerator::postvisit( AsmExpr * asmExpr ) {
741                if ( asmExpr->get_inout() ) {
742                        output << "[ ";
743                        asmExpr->get_inout()->accept( *visitor );
744                        output << " ] ";
745                } // if
746                asmExpr->get_constraint()->accept( *visitor );
747                output << " ( ";
748                asmExpr->get_operand()->accept( *visitor );
749                output << " )";
750        }
751
752        void CodeGenerator::postvisit( CompoundLiteralExpr *compLitExpr ) {
753                assert( compLitExpr->get_result() && dynamic_cast< ListInit * > ( compLitExpr->get_initializer() ) );
754                output << "(" << genType( compLitExpr->get_result(), "", pretty, genC ) << ")";
755                compLitExpr->get_initializer()->accept( *visitor );
756        }
757
758        void CodeGenerator::postvisit( UniqueExpr * unqExpr ) {
759                assertf( ! genC, "Unique expressions should not reach code generation." );
760                output << "unq<" << unqExpr->get_id() << ">{ ";
761                unqExpr->get_expr()->accept( *visitor );
762                output << " }";
763        }
764
765        void CodeGenerator::postvisit( StmtExpr * stmtExpr ) {
766                std::list< Statement * > & stmts = stmtExpr->get_statements()->get_kids();
767                output << "({" << endl;
768                ++indent;
769                unsigned int numStmts = stmts.size();
770                unsigned int i = 0;
771                for ( Statement * stmt : stmts ) {
772                        output << indent << printLabels( stmt->get_labels() );
773                        if ( i+1 == numStmts ) {
774                                // last statement in a statement expression needs to be handled specially -
775                                // cannot cast to void, otherwise the expression statement has no value
776                                if ( ExprStmt * exprStmt = dynamic_cast< ExprStmt * >( stmt ) ) {
777                                        exprStmt->get_expr()->accept( *visitor );
778                                        output << ";" << endl;
779                                        ++i;
780                                        break;
781                                }
782                        }
783                        stmt->accept( *visitor );
784                        output << endl;
785                        if ( wantSpacing( stmt ) ) {
786                                output << endl;
787                        } // if
788                        ++i;
789                }
790                --indent;
791                output << indent << "})";
792        }
793
794        void CodeGenerator::postvisit( ConstructorExpr * expr ) {
795                assertf( ! genC, "Unique expressions should not reach code generation." );
796                expr->callExpr->accept( *visitor );
797        }
798
799        // *** Statements
800        void CodeGenerator::postvisit( CompoundStmt * compoundStmt ) {
801                std::list<Statement*> ks = compoundStmt->get_kids();
802                output << "{" << endl;
803
804                ++indent;
805
806                for ( std::list<Statement *>::iterator i = ks.begin(); i != ks.end();  i++ ) {
807                        output << indent << printLabels( (*i)->get_labels() );
808                        (*i)->accept( *visitor );
809
810                        output << endl;
811                        if ( wantSpacing( *i ) ) {
812                                output << endl;
813                        } // if
814                } // for
815                --indent;
816
817                output << indent << "}";
818        }
819
820        void CodeGenerator::postvisit( ExprStmt * exprStmt ) {
821                assert( exprStmt );
822                if ( genC ) {
823                        // cast the top-level expression to void to reduce gcc warnings.
824                        exprStmt->set_expr( new CastExpr( exprStmt->get_expr() ) );
825                }
826                exprStmt->get_expr()->accept( *visitor );
827                output << ";";
828        }
829
830        void CodeGenerator::postvisit( AsmStmt * asmStmt ) {
831                output << "asm ";
832                if ( asmStmt->get_voltile() ) output << "volatile ";
833                if ( ! asmStmt->get_gotolabels().empty()  ) output << "goto ";
834                output << "( ";
835                if ( asmStmt->get_instruction() ) asmStmt->get_instruction()->accept( *visitor );
836                output << " : ";
837                genCommaList( asmStmt->get_output().begin(), asmStmt->get_output().end() );
838                output << " : ";
839                genCommaList( asmStmt->get_input().begin(), asmStmt->get_input().end() );
840                output << " : ";
841                genCommaList( asmStmt->get_clobber().begin(), asmStmt->get_clobber().end() );
842                if ( ! asmStmt->get_gotolabels().empty() ) {
843                        output << " : ";
844                        for ( std::list<Label>::iterator begin = asmStmt->get_gotolabels().begin();; ) {
845                                output << *begin++;
846                                if ( begin == asmStmt->get_gotolabels().end() ) break;
847                                output << ", ";
848                        } // for
849                } // if
850                output << " );" ;
851        }
852
853        void CodeGenerator::postvisit( AsmDecl * asmDecl ) {
854                output << "asm ";
855                AsmStmt * asmStmt = asmDecl->get_stmt();
856                output << "( ";
857                if ( asmStmt->get_instruction() ) asmStmt->get_instruction()->accept( *visitor );
858                output << " )" ;
859        }
860
861        void CodeGenerator::postvisit( IfStmt * ifStmt ) {
862                output << "if ( ";
863                ifStmt->get_condition()->accept( *visitor );
864                output << " ) ";
865
866                ifStmt->get_thenPart()->accept( *visitor );
867
868                if ( ifStmt->get_elsePart() != 0) {
869                        output << " else ";
870                        ifStmt->get_elsePart()->accept( *visitor );
871                } // if
872        }
873
874        void CodeGenerator::postvisit( SwitchStmt * switchStmt ) {
875                output << "switch ( " ;
876                switchStmt->get_condition()->accept( *visitor );
877                output << " ) ";
878
879                output << "{" << endl;
880                ++indent;
881                acceptAll( switchStmt->get_statements(), *visitor );
882                --indent;
883                output << indent << "}";
884        }
885
886        void CodeGenerator::postvisit( CaseStmt * caseStmt ) {
887                updateLocation( caseStmt );
888                output << indent;
889                if ( caseStmt->isDefault()) {
890                        output << "default";
891                } else {
892                        output << "case ";
893                        caseStmt->get_condition()->accept( *visitor );
894                } // if
895                output << ":" << endl;
896
897                std::list<Statement *> sts = caseStmt->get_statements();
898
899                ++indent;
900                for ( std::list<Statement *>::iterator i = sts.begin(); i != sts.end();  i++) {
901                        output << indent << printLabels( (*i)->get_labels() )  ;
902                        (*i)->accept( *visitor );
903                        output << endl;
904                } // for
905                --indent;
906        }
907
908        void CodeGenerator::postvisit( BranchStmt * branchStmt ) {
909                switch ( branchStmt->get_type()) {
910                  case BranchStmt::Goto:
911                        if ( ! branchStmt->get_target().empty() )
912                                output << "goto " << branchStmt->get_target();
913                        else {
914                                if ( branchStmt->get_computedTarget() != 0 ) {
915                                        output << "goto *";
916                                        branchStmt->get_computedTarget()->accept( *visitor );
917                                } // if
918                        } // if
919                        break;
920                  case BranchStmt::Break:
921                        output << "break";
922                        break;
923                  case BranchStmt::Continue:
924                        output << "continue";
925                        break;
926                } // switch
927                output << ";";
928        }
929
930        void CodeGenerator::postvisit( ReturnStmt * returnStmt ) {
931                output << "return ";
932                maybeAccept( returnStmt->get_expr(), *visitor );
933                output << ";";
934        }
935
936        void CodeGenerator::postvisit( ThrowStmt * throwStmt ) {
937                assertf( ! genC, "Throw statements should not reach code generation." );
938
939                output << ((throwStmt->get_kind() == ThrowStmt::Terminate) ?
940                           "throw" : "throwResume");
941                if (throwStmt->get_expr()) {
942                        output << " ";
943                        throwStmt->get_expr()->accept( *visitor );
944                }
945                if (throwStmt->get_target()) {
946                        output << " _At ";
947                        throwStmt->get_target()->accept( *visitor );
948                }
949                output << ";";
950        }
951        void CodeGenerator::postvisit( CatchStmt * stmt ) {
952                assertf( ! genC, "Catch statements should not reach code generation." );
953
954                output << ((stmt->get_kind() == CatchStmt::Terminate) ?
955                "catch" : "catchResume");
956                output << "( ";
957                stmt->decl->accept( *visitor );
958                output << " ) ";
959
960                if( stmt->cond ) {
961                        output << "if/when(?) (";
962                        stmt->cond->accept( *visitor );
963                        output << ") ";
964                }
965                stmt->body->accept( *visitor );
966        }
967
968        void CodeGenerator::postvisit( WaitForStmt * stmt ) {
969                assertf( ! genC, "Waitfor statements should not reach code generation." );
970
971                bool first = true;
972                for( auto & clause : stmt->clauses ) {
973                        if(first) { output << "or "; first = false; }
974                        if( clause.condition ) {
975                                output << "when(";
976                                stmt->timeout.condition->accept( *visitor );
977                                output << ") ";
978                        }
979                        output << "waitfor(";
980                        clause.target.function->accept( *visitor );
981                        for( Expression * expr : clause.target.arguments ) {
982                                output << ",";
983                                expr->accept( *visitor );
984                        }
985                        output << ") ";
986                        clause.statement->accept( *visitor );
987                }
988
989                if( stmt->timeout.statement ) {
990                        output << "or ";
991                        if( stmt->timeout.condition ) {
992                                output << "when(";
993                                stmt->timeout.condition->accept( *visitor );
994                                output << ") ";
995                        }
996                        output << "timeout(";
997                        stmt->timeout.time->accept( *visitor );
998                        output << ") ";
999                        stmt->timeout.statement->accept( *visitor );
1000                }
1001
1002                if( stmt->orelse.statement ) {
1003                        output << "or ";
1004                        if( stmt->orelse.condition ) {
1005                                output << "when(";
1006                                stmt->orelse.condition->accept( *visitor );
1007                                output << ")";
1008                        }
1009                        output << "else ";
1010                        stmt->orelse.statement->accept( *visitor );
1011                }
1012        }
1013
1014
1015        void CodeGenerator::postvisit( WhileStmt * whileStmt ) {
1016                if ( whileStmt->get_isDoWhile() ) {
1017                        output << "do" ;
1018                } else {
1019                        output << "while (" ;
1020                        whileStmt->get_condition()->accept( *visitor );
1021                        output << ")";
1022                } // if
1023                output << " ";
1024
1025                output << CodeGenerator::printLabels( whileStmt->get_body()->get_labels() );
1026                whileStmt->get_body()->accept( *visitor );
1027
1028                output << indent;
1029
1030                if ( whileStmt->get_isDoWhile() ) {
1031                        output << " while (" ;
1032                        whileStmt->get_condition()->accept( *visitor );
1033                        output << ");";
1034                } // if
1035        }
1036
1037        void CodeGenerator::postvisit( ForStmt * forStmt ) {
1038                // initialization is always hoisted, so don't bother doing anything with that
1039                output << "for (;";
1040
1041                if ( forStmt->get_condition() != 0 ) {
1042                        forStmt->get_condition()->accept( *visitor );
1043                } // if
1044                output << ";";
1045
1046                if ( forStmt->get_increment() != 0 ) {
1047                        // cast the top-level expression to void to reduce gcc warnings.
1048                        Expression * expr = new CastExpr( forStmt->get_increment() );
1049                        expr->accept( *visitor );
1050                } // if
1051                output << ") ";
1052
1053                if ( forStmt->get_body() != 0 ) {
1054                        output << CodeGenerator::printLabels( forStmt->get_body()->get_labels() );
1055                        forStmt->get_body()->accept( *visitor );
1056                } // if
1057        }
1058
1059        void CodeGenerator::postvisit( __attribute__((unused)) NullStmt * nullStmt ) {
1060                //output << indent << CodeGenerator::printLabels( nullStmt->get_labels() );
1061                output << "/* null statement */ ;";
1062        }
1063
1064        void CodeGenerator::postvisit( DeclStmt * declStmt ) {
1065                declStmt->get_decl()->accept( *visitor );
1066
1067                if ( doSemicolon( declStmt->get_decl() ) ) {
1068                        output << ";";
1069                } // if
1070        }
1071
1072        void CodeGenerator::postvisit( ImplicitCtorDtorStmt * stmt ) {
1073                assertf( ! genC, "ImplicitCtorDtorStmts should not reach code generation." );
1074                stmt->callStmt->accept( *visitor );
1075        }
1076
1077        void CodeGenerator::handleStorageClass( DeclarationWithType * decl ) {
1078                if ( decl->get_storageClasses().any() ) {
1079                        decl->get_storageClasses().print( output );
1080                } // if
1081        } // CodeGenerator::handleStorageClass
1082
1083        std::string genName( DeclarationWithType * decl ) {
1084                CodeGen::OperatorInfo opInfo;
1085                if ( operatorLookup( decl->get_name(), opInfo ) ) {
1086                        return opInfo.outputName;
1087                } else {
1088                        return decl->get_name();
1089                } // if
1090        }
1091} // namespace CodeGen
1092
1093
1094unsigned Indenter::tabsize = 2;
1095
1096std::ostream & operator<<( std::ostream & out, const BaseSyntaxNode * node ) {
1097        if ( node ) {
1098                node->print( out );
1099        } else {
1100                out << "nullptr";
1101        }
1102        return out;
1103}
1104
1105// Local Variables: //
1106// tab-width: 4 //
1107// mode: c++ //
1108// compile-command: "make install" //
1109// End: //
Note: See TracBrowser for help on using the repository browser.