source: src/CodeGen/CodeGenerator.cc @ ae32d96

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

Merge branch 'master' of plg.uwaterloo.ca:/u/cforall/software/cfa/cfa-cc

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