source: src/CodeGen/CodeGenerator.cc @ d807ca28

ADTaaron-thesisarm-ehast-experimentalcleanup-dtorsdeferred_resndemanglerenumforall-pointer-decayjacob/cs343-translationjenkins-sandboxnew-astnew-ast-unique-exprnew-envno_listpersistent-indexerpthread-emulationqualifiedEnumwith_gc
Last change on this file since d807ca28 was d807ca28, checked in by Rob Schluntz <rschlunt@…>, 6 years ago

Add AST support for _Generic, along with C codegen

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