source: src/CodeGen/CodeGenerator.cc @ 7991c7d

ADTast-experimentalpthread-emulationqualifiedEnum
Last change on this file since 7991c7d was b99fd56, checked in by Thierry Delisle <tdelisle@…>, 23 months ago

CodeGeneration? now generates variable exprs of type zero_t as litteral 0s.

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