source: src/CodeGen/CodeGenerator.cpp @ 59c8dff

Last change on this file since 59c8dff was 59c8dff, checked in by JiadaL <j82liang@…>, 6 months ago

Draft Implementation for enum position pesudo function (posE). EnumPosExpr? is mostly irrelevant for now. It is used in development/code probing and will be removed later

  • Property mode set to 100644
File size: 34.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.cpp --
8//
9// Author           : Andrew Beach
10// Created On       : Tue Oct 17 15:54:00 2023
11// Last Modified By : Andrew Beach
12// Last Modified On : Wed Oct 25 18:28:00 2023
13// Update Count     : 0
14//
15
16#include "CodeGenerator.hpp"
17
18#include "AST/Print.hpp"
19#include "OperatorTable.h"           // for OperatorInfo, operatorLookup
20#include "CodeGen/GenType.h"         // for genType
21#include "Common/ToString.hpp"       // for toString
22#include "Common/UniqueName.h"       // for UniqueName
23
24namespace CodeGen {
25
26int CodeGenerator::tabsize = 4;
27
28// The kinds of statements that should be followed by whitespace.
29static bool wantSpacing( ast::Stmt const * stmt ) {
30        return dynamic_cast<ast::IfStmt const *>( stmt )
31                || dynamic_cast<ast::CompoundStmt const *>( stmt )
32                || dynamic_cast<ast::WhileDoStmt const *>( stmt )
33                || dynamic_cast<ast::ForStmt const *>( stmt )
34                || dynamic_cast<ast::SwitchStmt const *>( stmt );
35}
36
37void CodeGenerator::extension( ast::Expr const * expr ) {
38        if ( expr->extension ) output << "__extension__ ";
39}
40
41void CodeGenerator::extension( ast::Decl const * decl ) {
42        if ( decl->extension ) output << "__extension__ ";
43}
44
45void CodeGenerator::asmName( ast::DeclWithType const * decl ) {
46        if ( auto asmName = decl->asmName.as<ast::ConstantExpr>() ) {
47                output << " asm ( " << asmName->rep << " )";
48        }
49}
50
51CodeGenerator::LabelPrinter & CodeGenerator::LabelPrinter::operator()(
52                std::vector<ast::Label> const & l ) {
53        labels = &l;
54        return *this;
55}
56
57std::ostream & CodeGenerator::LabelPrinter::operator()( std::ostream & output ) const {
58        const std::vector<ast::Label> & labels = *this->labels;
59        for ( const ast::Label & label : labels ) {
60                output << label.name + ": ";
61                this->cg.genAttributes( label.attributes );
62        }
63        return output;
64}
65
66// Using updateLocation at the beginning of a node and endl within a node
67// should become the method of formating.
68void CodeGenerator::updateLocation( CodeLocation const & to ) {
69        // Skip if linemarks shouldn't appear or if location is unset.
70        if ( !options.lineMarks || to.isUnset() ) return;
71
72        if ( currentLocation.followedBy( to, 0 ) ) {
73                return;
74        } else if ( currentLocation.followedBy( to, 1 ) ) {
75                output << "\n" << indent;
76                currentLocation.first_line += 1;
77        } else if ( currentLocation.followedBy( to, 2 ) ) {
78                output << "\n\n" << indent;
79                currentLocation.first_line += 2;
80        } else {
81                output << "\n# " << to.first_line << " \"" << to.filename
82                       << "\"\n" << indent;
83                currentLocation = to;
84        }
85        output << std::flush;
86}
87
88void CodeGenerator::updateLocation( ast::ParseNode const * to ) {
89        updateLocation( to->location );
90}
91
92std::ostream & CodeGenerator::LineEnder::operator()( std::ostream & os ) const {
93        os << "\n" << std::flush;
94        cg.currentLocation.first_line++;
95        return os;
96}
97
98CodeGenerator::CodeGenerator( std::ostream & os, const Options & options ) :
99                indent( 0, CodeGenerator::tabsize ), output( os ),
100                options( options ), printLabels( *this ), endl( *this )
101{}
102
103std::string CodeGenerator::mangleName( ast::DeclWithType const * decl ) {
104        if ( !options.pretty && decl->linkage.is_mangled && decl->mangleName != "" ) {
105                return decl->scopedMangleName();
106        } else {
107                return decl->name;
108        }
109}
110
111void CodeGenerator::genAttributes(
112                const std::vector<ast::ptr<ast::Attribute>> & attributes ) {
113        if ( attributes.empty() ) return;
114        output << "__attribute__ ((";
115        for ( auto attr = attributes.begin() ;; ) {
116                output << (*attr)->name;
117                if ( !(*attr)->params.empty() ) {
118                        output << "(";
119                        genCommaList( (*attr)->params );
120                        output << ")";
121                }
122                if ( ++attr == attributes.end() ) break;
123                output << ",";
124        }
125        output << ")) ";
126}
127
128void CodeGenerator::previsit( ast::Node const * ) {
129        // All traversal is manual.
130        // TODO: Which means the ast::Pass is just providing a default no visit?
131        visit_children = false;
132}
133
134void CodeGenerator::previsit( ast::ParseNode const * node ) {
135        previsit( (ast::Node const *)node );
136        updateLocation( node );
137}
138
139void CodeGenerator::postvisit( ast::Node const * node ) {
140        std::stringstream ss;
141        ast::print( ss, node );
142        assertf( false, "Unhandled node reached in CodeGenerator: %s", ss.str().c_str() );
143}
144
145void CodeGenerator::previsit( ast::Expr const * expr ) {
146        previsit( (ast::ParseNode const *)expr );
147        GuardAction( [this, expr](){
148                if ( options.printExprTypes && expr->result ) {
149                        output << " /* " << genType( expr->result, "", options ) << " */ ";
150                }
151        } );
152}
153
154void CodeGenerator::postvisit( ast::FunctionDecl const * decl ) {
155        // Deleted decls should never be used, so don't print them in C.
156        if ( decl->isDeleted && options.genC ) return;
157        extension( decl );
158        genAttributes( decl->attributes );
159
160        handleStorageClass( decl );
161        ast::print( output, decl->funcSpec );
162
163        Options subOptions = options;
164        subOptions.anonymousUnused = decl->stmts;
165
166        std::ostringstream acc;
167        ast::Pass<CodeGenerator> subCG( acc, subOptions );
168        // Add the forall clause.
169        // TODO: These probably should be removed by now and the assert used.
170        if ( !decl->type_params.empty() ) {
171                assertf( !options.genC, "FunctionDecl forall should not reach code generation." );
172                acc << "forall(";
173                subCG.core.genCommaList( decl->type_params );
174                acc << ")" << std::endl;
175        }
176
177        acc << mangleName( decl );
178
179        if ( 0 == decl->params.size() ) {
180                if ( decl->type->isVarArgs ) {
181                        acc << "()";
182                } else {
183                        acc << "(void)";
184                }
185        } else {
186                acc << "(";
187                subCG.core.genCommaList( decl->params );
188                if ( decl->type->isVarArgs ) {
189                        acc << ", ...";
190                }
191                acc << ")";
192        }
193
194        assert( decl->returns.size() < 2 );
195        if ( 1 == decl->returns.size() ) {
196                ast::ptr<ast::Type> const & type = decl->returns[0]->get_type();
197                output << genTypeNoAttr( type, acc.str(), subOptions );
198        } else {
199                output << "void " + acc.str();
200        }
201
202        asmName( decl );
203
204        if ( decl->stmts ) {
205                decl->stmts->accept( *visitor );
206        }
207        if ( decl->isDeleted ) {
208                output << " = void";
209        }
210}
211
212ast::ObjectDecl const * CodeGenerator::postvisit(
213                ast::ObjectDecl const * decl ) {
214        // Deleted decls should never be used, so don't print them in C.
215        if ( decl->isDeleted && options.genC ) return decl;
216
217        // GCC allows an empty declarator (no name) for bit-fields and C
218        // states: 6.7.2.1 Structure and union specifiers, point 4, page 113:
219        // If the (bit field) value is zero, the declaration shall have no
220        // declarator. For anything else, the anonymous name refers to the
221        // anonymous object for plan9 inheritance.
222        if ( decl->name.empty() && options.genC && !decl->bitfieldWidth ) {
223                // TODO: Should this be changed in a pervious pass?
224                auto mutDecl = ast::mutate( decl );
225                // Only generate an anonymous name when generating C code,
226                // otherwise it clutters the output too much.
227                static UniqueName name = { "__anonymous_object" };
228                mutDecl->name = name.newName();
229                // Stops unused parameter warnings.
230                if ( options.anonymousUnused ) {
231                        mutDecl->attributes.push_back( new ast::Attribute( "unused" ) );
232                }
233                decl = mutDecl;
234        }
235
236        extension( decl );
237        genAttributes( decl->attributes );
238
239        handleStorageClass( decl );
240        output << genType( decl->type, mangleName( decl ),
241                Options( options.pretty, options.genC, false, false ) );
242
243        asmName( decl );
244
245        if ( decl->init ) {
246                output << " = ";
247                decl->init->accept( *visitor );
248        }
249        if ( decl->isDeleted ) {
250                output << " = void";
251        }
252
253        if ( decl->bitfieldWidth ) {
254                output << ":";
255                decl->bitfieldWidth->accept( *visitor );
256        }
257        return decl;
258}
259
260void CodeGenerator::handleStorageClass( ast::DeclWithType const * decl ) {
261        if ( decl->storage.any() ) {
262                ast::print( output, decl->storage );
263        }
264}
265
266void CodeGenerator::handleAggregate(
267                ast::AggregateDecl const * decl, std::string const & kind ) {
268        if ( !decl->params.empty() && !options.genC ) {
269                output << "forall(";
270                genCommaList( decl->params );
271                output << ")\n" << indent << std::flush;
272        }
273
274        output << kind;
275        genAttributes( decl->attributes );
276        output << decl->name;
277
278        if ( decl->body ) {
279                auto & members = decl->members;
280                output << " {" << endl;
281
282                ++indent;
283                for ( auto & member : members ) {
284                        output << indent;
285                        member->accept( *visitor );
286                        output << ";" << endl;
287                }
288                --indent;
289
290                output << indent << "}";
291        }
292}
293
294void CodeGenerator::postvisit( ast::StructDecl const * decl ) {
295        extension( decl );
296        handleAggregate( decl, "struct " );
297}
298
299void CodeGenerator::postvisit( ast::UnionDecl const * decl ) {
300        extension( decl );
301        handleAggregate( decl, "union " );
302}
303
304template<typename pass_type>
305inline void genEnumInitializer( ast::Pass<pass_type> * visitor,
306                ast::Type const * baseType, std::ostream & output,
307                ast::Init const * init, long long * curVal, Options options ) {
308        auto baseTypeAsBasic = dynamic_cast<ast::BasicType const *>( baseType );
309        // Value is provided.
310        if ( init ) {
311                output << " = (" << genType( baseType, "", options ) << ")";
312                init->accept( *visitor );
313                // If it is an integral type and initilizer offered,
314                // need to update the curVal.
315                if ( baseTypeAsBasic && baseTypeAsBasic->isInteger() ) {
316                        ast::Expr const * expr = ((ast::SingleInit const *)(init))->value;
317                        // Unwrap introduced cast.
318                        while ( auto temp = dynamic_cast<ast::CastExpr const *>( expr ) ) {
319                                expr = temp->arg;
320                        }
321                        *curVal = ((ast::ConstantExpr const *)(expr))->intValue() + 1;
322                }
323        // Generate next value from previous value.
324        } else if ( baseTypeAsBasic && baseTypeAsBasic->isInteger() ) {
325                output << " = (" << genType( baseType, "", options ) << ")";
326                output << (*curVal)++;
327        }
328}
329
330void CodeGenerator::postvisit( ast::EnumDecl const * decl ) {
331        extension( decl );
332        auto members = decl->members;
333        if ( decl->base && !members.empty() ) {
334                long long curVal = 0;
335                for ( auto member : members ) {
336                        auto obj = member.strict_as<ast::ObjectDecl>();
337                        output << "static ";
338                        output << genType( decl->base, mangleName( obj ), options );
339                        genEnumInitializer( visitor, decl->base, output, obj->init, &curVal, options );
340                        output << ";" << endl;
341                }
342        } else {
343                output << "enum ";
344                genAttributes( decl->attributes );
345
346                output << decl->name;
347
348                if ( !members.empty() ) {
349                        output << " {" << endl;
350
351                        ++indent;
352                        for ( auto member : members ) {
353                                auto obj = member.strict_as<ast::ObjectDecl>();
354                                output << indent << mangleName( obj );
355                                if ( obj->init ) {
356                                        output << " = ";
357                                        obj->init->accept( *visitor );
358                                }
359                                output << "," << endl;
360                        }
361                        --indent;
362
363                        output << indent << "}";
364                }
365        }
366}
367
368void CodeGenerator::postvisit( ast::TraitDecl const * decl ) {
369        assertf( !options.genC, "TraitDecls should not reach code generation." );
370        extension( decl );
371        handleAggregate( decl, "trait " );
372}
373
374void CodeGenerator::postvisit( ast::TypedefDecl const * decl ) {
375        assertf( !options.genC, "Typedefs should not reach code generation." );
376        output << "typedef " << genType( decl->base, decl->name, options ) << endl;
377}
378
379void CodeGenerator::postvisit( ast::TypeDecl const * decl ) {
380        assertf( !options.genC, "TypeDecls should not reach code generation." );
381        output << decl->genTypeString() << " " << decl->name;
382        if ( decl->sized ) {
383                output << " | sized(" << decl->name << ")";
384        }
385        if ( !decl->assertions.empty() ) {
386                output << " | { ";
387                for ( ast::DeclWithType const * assert : decl->assertions ) {
388                        assert->accept( *visitor );
389                        output << "; ";
390                }
391                output << " }";
392        }
393}
394
395void CodeGenerator::postvisit( ast::StaticAssertDecl const * decl ) {
396        output << "_Static_assert(";
397        decl->cond->accept( *visitor );
398        output << ", ";
399        decl->msg->accept( *visitor );
400        output << ")";
401}
402
403void CodeGenerator::postvisit( ast::Designation const * designation ) {
404        auto designators = designation->designators;
405        if ( 0 == designators.size() ) return;
406        for ( ast::ptr<ast::Expr> const & des : designators ) {
407                // If the expression is a NameExpr or VariableExpr, then it is a field.
408                if ( des.as<ast::NameExpr>() || des.as<ast::VariableExpr>() ) {
409                        output << ".";
410                        des->accept( *visitor );
411                // Otherwise, it is a ConstantExpr or CastExpr, then it is an index.
412                } else {
413                        output << "[";
414                        des->accept( *visitor );
415                        output << "]";
416                }
417        }
418        output << " = ";
419}
420
421void CodeGenerator::postvisit( ast::SingleInit const * init ) {
422        init->value->accept( *visitor );
423}
424
425void CodeGenerator::postvisit( ast::ListInit const * init ) {
426        auto initBegin = init->initializers.begin();
427        auto initEnd = init->initializers.end();
428        auto desigBegin = init->designations.begin();
429        auto desigEnd = init->designations.end();
430
431        output << "{ ";
432        if ( initBegin != initEnd ) while (true) {
433                (*desigBegin)->accept( *visitor );
434                (*initBegin)->accept( *visitor );
435                ++initBegin, ++desigBegin;
436                if ( initBegin == initEnd ) break;
437                output << ", ";
438        }
439        output << " }";
440        assertf( initBegin == initEnd && desigBegin == desigEnd,
441                "Initializers and designators not the same length. %s", toCString( init ) );
442}
443
444void CodeGenerator::postvisit( ast::ConstructorInit const * init ) {
445        assertf( !options.genC, "ConstructorInit nodes should not reach code generation." );
446        // This isn't actual code, but labels the constructor/destructor pairs.
447        output << "<ctorinit>{" << endl << ++indent << "ctor: ";
448        if ( init->ctor ) init->ctor->accept( *visitor );
449        output << ", " << endl << indent << "dtor: ";
450        if ( init->dtor ) init->dtor->accept( *visitor );
451        output << endl << --indent << "}";
452}
453
454void CodeGenerator::postvisit( ast::ApplicationExpr const * expr ) {
455        extension( expr );
456        if ( auto var = expr->func.as<ast::VariableExpr>() ) {
457                const OperatorInfo * opInfo;
458                if ( var->var->linkage == ast::Linkage::Intrinsic &&
459                                ( opInfo = operatorLookup( var->var->name ) ) ) {
460                        auto arg = expr->args.begin();
461                        switch ( opInfo->type ) {
462                        case OT_INDEX:
463                                assert( 2 == expr->args.size() );
464                                (*arg++)->accept( *visitor );
465                                output << "[";
466                                (*arg)->accept( *visitor );
467                                output << "]";
468                                break;
469
470                        // There are no intrinsic definitions of the function call operator.
471                        case OT_CALL:
472                                assert( false );
473                                break;
474
475                        case OT_CTOR:
476                        case OT_DTOR:
477                                // No-op constructor, but run the internal expression.
478                                if ( 1 == expr->args.size() ) {
479                                        output << "(";
480                                        (*arg++)->accept( *visitor );
481                                        output << ") /* " << opInfo->inputName << " */";
482                                // These are all implemented as some form of assignment.
483                                } else if ( 2 == expr->args.size() ) {
484                                        output << "(";
485                                        (*arg++)->accept( *visitor );
486                                        output << opInfo->symbol;
487                                        (*arg)->accept( *visitor );
488                                        output << ") /* " << opInfo->inputName << " */";
489                                // No constructors with 0 or more than 2 parameters.
490                                } else {
491                                        assert( false );
492                                }
493                                break;
494
495                        case OT_PREFIX:
496                        case OT_PREFIXASSIGN:
497                                assert( 1 == expr->args.size() );
498                                output << "(" << opInfo->symbol;
499                                (*arg)->accept( *visitor );
500                                output << ")";
501                                break;
502
503                        case OT_POSTFIX:
504                        case OT_POSTFIXASSIGN:
505                                assert( 1 == expr->args.size() );
506                                (*arg)->accept( *visitor );
507                                output << opInfo->symbol;
508                                break;
509
510                        case OT_INFIX:
511                        case OT_INFIXASSIGN:
512                                assert( 2 == expr->args.size() );
513                                output << "(";
514                                (*arg++)->accept( *visitor );
515                                output << opInfo->symbol;
516                                (*arg)->accept( *visitor );
517                                output << ")";
518                                break;
519
520                        // There are no intrinsic definitions of 0/1 or label address
521                        // as function.
522                        case OT_CONSTANT:
523                        case OT_LABELADDRESS:
524                                assert( false );
525                        }
526                // TODO: This is a work-around to make it a constant until a proper
527                // constexpr solution is created.
528                } else if ( var->var->linkage == ast::Linkage::BuiltinCFA &&
529                                var->var->name == "intptr" ) {
530                        output << "((void*)";
531                        auto arg = expr->args.begin();
532                        (*arg++)->accept( *visitor );
533                        output << ")";
534                } else {
535                        var->accept( *visitor );
536                        output << "(";
537                        genCommaList( expr->args );
538                        output << ")";
539                }
540        } else {
541                expr->func->accept( *visitor );
542                output << "(";
543                genCommaList( expr->args );
544                output << ")";
545        }
546}
547
548void CodeGenerator::postvisit( ast::UntypedExpr const * expr ) {
549        extension( expr );
550        if ( auto name = expr->func.as<ast::NameExpr>() ) {
551                if ( const OperatorInfo * opInfo = operatorLookup( name->name ) ) {
552                        auto arg = expr->args.begin();
553                        switch ( opInfo->type ) {
554                        case OT_INDEX:
555                                assert( 2 == expr->args.size() );
556                                (*arg++)->accept( *visitor );
557                                output << "[";
558                                (*arg)->accept( *visitor );
559                                output << "]";
560                                break;
561
562                        case OT_CALL:
563                                assert( false );
564
565                        case OT_CTOR:
566                        case OT_DTOR:
567                                // No-op constructor, but run the internal expression.
568                                if ( 1 == expr->args.size() ) {
569                                        output << "(";
570                                        (*arg++)->accept( *visitor );
571                                        output << ")";
572                                // These are all implemented as some form of assignment.
573                                } else if ( 2 == expr->args.size() ) {
574                                        output << "(";
575                                        (*arg++)->accept( *visitor );
576                                        output << opInfo->symbol;
577                                        (*arg)->accept( *visitor );
578                                        output << ") /* " << opInfo->inputName << " */";
579                                // No constructors with 0 or more than 2 parameters.
580                                } else {
581                                        assertf( !options.genC, "UntypedExpr constructor/destructor with 0 or more than 2 parameters." );
582                                        output << "(";
583                                        (*arg++)->accept( *visitor );
584                                        output << opInfo->symbol << "{ ";
585                                        genCommaList( arg, expr->args.end() );
586                                        output << "}) /* " << opInfo->inputName << " */";
587                                }
588                                break;
589
590                        case OT_PREFIX:
591                        case OT_PREFIXASSIGN:
592                        case OT_LABELADDRESS:
593                                assert( 1 == expr->args.size() );
594                                output << "(" << opInfo->symbol;
595                                (*arg)->accept( *visitor );
596                                output << ")";
597                                break;
598
599                        case OT_POSTFIX:
600                        case OT_POSTFIXASSIGN:
601                                assert( 1 == expr->args.size() );
602                                (*arg)->accept( *visitor );
603                                output << opInfo->symbol;
604                                break;
605
606                        case OT_INFIX:
607                        case OT_INFIXASSIGN:
608                                assert( 2 == expr->args.size() );
609                                output << "(";
610                                (*arg++)->accept( *visitor );
611                                output << opInfo->symbol;
612                                (*arg)->accept( *visitor );
613                                output << ")";
614                                break;
615
616                        // There are no intrinsic definitions of 0/1 or label address
617                        // as function.
618                        case OT_CONSTANT:
619                                assert( false );
620                        }
621                // builtin routines
622                } else {
623                        name->accept( *visitor );
624                        output << "(";
625                        genCommaList( expr->args );
626                        output << ")";
627                }
628        } else {
629                expr->func->accept( *visitor );
630                output << "(";
631                genCommaList( expr->args );
632                output << ")";
633        }
634}
635
636void CodeGenerator::postvisit( ast::RangeExpr const * expr ) {
637        expr->low->accept( *visitor );
638        output << " ... ";
639        expr->high->accept( *visitor );
640}
641
642void CodeGenerator::postvisit( ast::NameExpr const * expr ) {
643        extension( expr );
644        if ( const OperatorInfo * opInfo = operatorLookup( expr->name ) ) {
645                if ( OT_CONSTANT == opInfo->type ) {
646                        output << opInfo->symbol;
647                } else {
648                        output << opInfo->outputName;
649                }
650        } else {
651                output << expr->name;
652        }
653}
654
655void CodeGenerator::postvisit( ast::DimensionExpr const * expr ) {
656        extension( expr );
657        output << "/*non-type*/" << expr->name;
658}
659
660void CodeGenerator::postvisit( ast::AddressExpr const * expr ) {
661        extension( expr );
662        output << "(&";
663        expr->arg->accept( *visitor );
664        output << ")";
665}
666
667void CodeGenerator::postvisit( ast::LabelAddressExpr const * expr ) {
668        extension( expr );
669        output << "(&&" << expr->arg << ")";
670}
671
672void CodeGenerator::postvisit( ast::CastExpr const * expr ) {
673        extension( expr );
674        output << "(";
675        if ( expr->result->isVoid() ) {
676                output << "(void)";
677        } else {
678                output << "(";
679                output << genType( expr->result, "", options );
680                output << ")";
681        }
682        expr->arg->accept( *visitor );
683        output << ")";
684}
685
686void CodeGenerator::postvisit( ast::KeywordCastExpr const * expr ) {
687        assertf( !options.genC, "KeywordCastExpr should not reach code generation." );
688        extension( expr );
689        output << "((" << expr->targetString() << " &)";
690        expr->arg->accept( *visitor );
691        output << ")";
692}
693
694void CodeGenerator::postvisit( ast::VirtualCastExpr const * expr ) {
695        assertf( !options.genC, "VirtualCastExpr should not reach code generation." );
696        extension( expr );
697        // TODO: Is this busted?
698        output << "(virtual ";
699        expr->arg->accept( *visitor );
700        output << ")";
701}
702
703void CodeGenerator::postvisit( ast::UntypedMemberExpr const * expr ) {
704        assertf( !options.genC, "UntypedMemberExpr should not reach code generation." );
705        extension( expr );
706        expr->aggregate->accept( *visitor );
707        output << ".";
708        expr->member->accept( *visitor );
709}
710
711void CodeGenerator::postvisit( ast::MemberExpr const * expr ) {
712        extension( expr );
713        expr->aggregate->accept( *visitor );
714        output << "." << mangleName( expr->member );
715}
716
717void CodeGenerator::postvisit( ast::VariableExpr const * expr ) {
718        extension( expr );
719        const OperatorInfo * opInfo;
720        if ( dynamic_cast<ast::ZeroType const *>( expr->var->get_type() ) ) {
721                output << "0";
722        } else if ( expr->var->linkage == ast::Linkage::Intrinsic
723                        && ( opInfo = operatorLookup( expr->var->name ) )
724                        && opInfo->type == OT_CONSTANT ) {
725                output << opInfo->symbol;
726        } else {
727                output << mangleName( expr->var );
728        }
729}
730
731void CodeGenerator::postvisit( ast::ConstantExpr const * expr ) {
732        extension( expr );
733        output << expr->rep;
734}
735
736void CodeGenerator::postvisit( ast::SizeofExpr const * expr ) {
737        extension( expr );
738        output << "sizeof(";
739        if ( expr->type ) {
740                output << genType( expr->type, "", options );
741        } else {
742                expr->expr->accept( *visitor );
743        }
744        output << ")";
745}
746
747void CodeGenerator::postvisit( ast::AlignofExpr const * expr ) {
748        // Using the GCC extension to avoid changing the std to C11.
749        extension( expr );
750        output << "__alignof__(";
751        if ( expr->type ) {
752                output << genType( expr->type, "", options );
753        } else {
754                expr->expr->accept( *visitor );
755        }
756        output << ")";
757}
758
759void CodeGenerator::postvisit( ast::UntypedOffsetofExpr const * expr ) {
760        assertf( !options.genC, "UntypedOffsetofExpr should not reach code generation." );
761        output << "offsetof(";
762        output << genType( expr->type, "", options );
763        output << ", " << expr->member;
764        output << ")";
765}
766
767void CodeGenerator::postvisit( ast::OffsetofExpr const * expr ) {
768        // Use GCC builtin
769        output << "__builtin_offsetof(";
770        output << genType( expr->type, "", options );
771        output << ", " << mangleName( expr->member );
772        output << ")";
773}
774
775void CodeGenerator::postvisit( ast::OffsetPackExpr const * expr ) {
776        assertf( !options.genC, "OffsetPackExpr should not reach code generation." );
777        output << "__CFA_offsetpack(" << genType( expr->type, "", options ) << ")";
778}
779
780void CodeGenerator::postvisit( ast::EnumPosExpr const * expr ) {
781        assertf( !options.genC, "EnumPosExpr should not reach code generation." );
782        output << "__CFA_enumeration_pos(" << genType( expr->type, "", options ) << ")";
783}
784
785void CodeGenerator::postvisit( ast::LogicalExpr const * expr ) {
786        extension( expr );
787        output << "(";
788        expr->arg1->accept( *visitor );
789        output << ( ( expr->isAnd ) ? " && " : " || " );
790        expr->arg2->accept( *visitor );
791        output << ")";
792}
793
794void CodeGenerator::postvisit( ast::ConditionalExpr const * expr ) {
795        extension( expr );
796        output << "(";
797        expr->arg1->accept( *visitor );
798        output << " ? ";
799        expr->arg2->accept( *visitor );
800        output << " : ";
801        expr->arg3->accept( *visitor );
802        output << ")";
803}
804
805void CodeGenerator::postvisit( ast::CommaExpr const * expr ) {
806        extension( expr );
807        output << "(";
808        if ( options.genC ) {
809                // arg1 of a comma expression is never used, so it can be safely cast
810                // to void to reduce gcc warnings.
811                ast::ptr<ast::Expr> arg1 = new ast::CastExpr( expr->location, expr->arg1 );
812                arg1->accept( *visitor );
813        } else {
814                expr->arg1->accept( *visitor );
815        }
816        output << " , ";
817        expr->arg2->accept( *visitor );
818        output << ")";
819}
820
821void CodeGenerator::postvisit( ast::TupleAssignExpr const * expr ) {
822        assertf( !options.genC, "TupleAssignExpr should not reach code generation." );
823        expr->stmtExpr->accept( *visitor );
824}
825
826void CodeGenerator::postvisit( ast::UntypedTupleExpr const * expr ) {
827        assertf( !options.genC, "UntypedTupleExpr should not reach code generation." );
828        extension( expr );
829        output << "[";
830        genCommaList( expr->exprs );
831        output << "]";
832}
833
834void CodeGenerator::postvisit( ast::TupleExpr const * expr ) {
835        assertf( !options.genC, "TupleExpr should not reach code generation." );
836        extension( expr );
837        output << "[";
838        genCommaList( expr->exprs );
839        output << "]";
840}
841
842void CodeGenerator::postvisit( ast::TupleIndexExpr const * expr ) {
843        assertf( !options.genC, "TupleIndexExpr should not reach code generation." );
844        extension( expr );
845        expr->tuple->accept( *visitor );
846        output << "." << expr->index;
847}
848
849void CodeGenerator::postvisit( ast::TypeExpr const * expr ) {
850        // TODO: Should there be an assertion there?
851        if ( !options.genC ) {
852                output << genType( expr->type, "", options );
853        }
854}
855
856void CodeGenerator::postvisit( ast::AsmExpr const * expr ) {
857        if ( !expr->inout.empty() ) {
858                output << "[ " << expr->inout << " ] ";
859        }
860        expr->constraint->accept( *visitor );
861        output << " ( ";
862        expr->operand->accept( *visitor );
863        output << " )";
864}
865
866void CodeGenerator::postvisit( ast::CompoundLiteralExpr const * expr ) {
867        //assert( expr->result && dynamic_cast<ast::ListInit const *>( expr->init ) );
868        assert( expr->result && expr->init.as<ast::ListInit>() );
869        output << "(" << genType( expr->result, "", options ) << ")";
870        expr->init->accept( *visitor );
871}
872
873void CodeGenerator::postvisit( ast::UniqueExpr const * expr ) {
874        assertf( !options.genC, "UniqueExpr should not reach code generation." );
875        output << "unq<" << expr->id << ">{ ";
876        expr->expr->accept( *visitor );
877        output << " }";
878}
879
880void CodeGenerator::postvisit( ast::StmtExpr const * expr ) {
881        auto stmts = expr->stmts->kids;
882        output << "({" << endl;
883        ++indent;
884        unsigned int numStmts = stmts.size();
885        unsigned int i = 0;
886        for ( ast::ptr<ast::Stmt> const & stmt : stmts ) {
887                output << indent << printLabels( stmt->labels );
888                if ( i + 1 == numStmts ) {
889                        // Last statement in a statement expression needs to be handled
890                        // specially - cannot cast to void, otherwise the expression
891                        // statement has no value.
892                        if ( ast::ExprStmt const * exprStmt = stmt.as<ast::ExprStmt>() ) {
893                                exprStmt->expr->accept( *visitor );
894                                output << ";" << endl;
895                                ++i;
896                                break;
897                        }
898                }
899                stmt->accept( *visitor );
900                output << endl;
901                if ( wantSpacing( stmt ) ) output << endl;
902                ++i;
903        }
904        --indent;
905        output << indent << "})";
906}
907
908void CodeGenerator::postvisit( ast::ConstructorExpr const * expr ) {
909        assertf( !options.genC, "ConstructorExpr should not reach code generation." );
910        expr->callExpr->accept( *visitor );
911}
912
913void CodeGenerator::postvisit( ast::DeletedExpr const * expr ) {
914        assertf( !options.genC, "DeletedExpr should not reach code generation." );
915        expr->expr->accept( *visitor );
916}
917
918void CodeGenerator::postvisit( ast::DefaultArgExpr const * expr ) {
919        assertf( !options.genC, "DefaultArgExpr should not reach code generation." );
920        expr->expr->accept( *visitor );
921}
922
923void CodeGenerator::postvisit( ast::GenericExpr const * expr ) {
924        assertf( !options.genC, "GenericExpr should not reach code generation." );
925        output << "_Generic(";
926        expr->control->accept( *visitor );
927        output << ", ";
928        unsigned int numAssocs = expr->associations.size();
929        unsigned int i = 0;
930        for ( const ast::GenericExpr::Association & assoc : expr->associations ) {
931                if ( nullptr == assoc.type ) {
932                        output << "default: ";
933                } else {
934                        output << genType( assoc.type, "", options ) << ": ";
935                }
936                assoc.expr->accept( *visitor );
937                ++i;
938                if ( i != numAssocs ) output << ", ";
939        }
940        output << ")";
941}
942
943void CodeGenerator::postvisit( ast::CompoundStmt const * stmt ) {
944        output << "{" << endl;
945
946        ++indent;
947        for ( auto kid : stmt->kids ) {
948                output << indent << printLabels( kid->labels );
949                kid->accept( *visitor );
950                output << endl;
951                if ( wantSpacing( kid ) ) output << endl;
952        }
953        --indent;
954
955        output << indent << "}";
956}
957
958void CodeGenerator::postvisit( ast::ExprStmt const * stmt ) {
959        assert( stmt );
960        // Cast the top-level expression to void to reduce gcc warnings.
961        if ( options.genC ) {
962                ast::ptr<ast::Expr> expr = new ast::CastExpr( stmt->location, stmt->expr );
963                expr->accept( *visitor );
964        } else {
965                stmt->expr->accept( *visitor );
966        }
967        output << ";";
968}
969
970void CodeGenerator::postvisit( ast::AsmStmt const * stmt ) {
971        output << "asm ";
972        if ( stmt->isVolatile ) output << "volatile ";
973        if ( !stmt->gotoLabels.empty() ) output << "goto ";
974        output << "( ";
975        if ( stmt->instruction ) stmt->instruction->accept( *visitor );
976        output << " : ";
977        genCommaList( stmt->output );
978        output << " : ";
979        genCommaList( stmt->input );
980        output << " : ";
981        genCommaList( stmt->clobber );
982        if ( !stmt->gotoLabels.empty() ) {
983                output << " : ";
984                auto it = stmt->gotoLabels.begin();
985                while (true) {
986                        output << *it++;
987                        if ( stmt->gotoLabels.end() == it ) break;
988                        output << ", ";
989                }
990        }
991        output << " );";
992}
993
994void CodeGenerator::postvisit( ast::AsmDecl const * decl ) {
995        output << "asm ";
996        ast::AsmStmt const * stmt = decl->stmt;
997        output << "( ";
998        if ( stmt->instruction ) stmt->instruction->accept( *visitor );
999        output << " )";
1000}
1001
1002void CodeGenerator::postvisit( ast::DirectiveDecl const * decl ) {
1003        // endl prevents spaces before the directive.
1004        output << endl << decl->stmt->directive;
1005}
1006
1007void CodeGenerator::postvisit( ast::DirectiveStmt const * stmt ) {
1008        // endl prevents spaces before the directive.
1009        output << endl << stmt->directive;
1010}
1011
1012void CodeGenerator::postvisit( ast::IfStmt const * stmt ) {
1013        output << "if ( ";
1014        stmt->cond->accept( *visitor );
1015        output << " ) ";
1016
1017        stmt->then->accept( *visitor );
1018
1019        if ( nullptr != stmt->else_ ) {
1020                output << " else ";
1021                stmt->else_->accept( *visitor );
1022        }
1023}
1024
1025void CodeGenerator::postvisit( ast::SwitchStmt const * stmt ) {
1026        output << "switch ( ";
1027        stmt->cond->accept( *visitor );
1028        output << " ) ";
1029
1030        output << "{" << endl;
1031        ++indent;
1032        for ( auto node : stmt->cases ) {
1033                node->accept( *visitor );
1034        }
1035        --indent;
1036        output << indent << "}";
1037}
1038
1039void CodeGenerator::postvisit( ast::CaseClause const * clause ) {
1040        updateLocation( clause );
1041        output << indent;
1042        if ( clause->isDefault() ) {
1043                output << "default";
1044        } else {
1045                output << "case ";
1046                clause->cond->accept( *visitor );
1047        }
1048        output << ":" << endl;
1049
1050        ++indent;
1051        for ( auto stmt : clause->stmts ) {
1052                output << indent << printLabels( stmt->labels ) ;
1053                stmt->accept( *visitor );
1054                output << endl;
1055        }
1056        --indent;
1057}
1058
1059void CodeGenerator::postvisit( ast::BranchStmt const * stmt ) {
1060        switch ( stmt->kind ) {
1061        case ast::BranchStmt::Goto:
1062                if ( !stmt->target.empty() ) {
1063                        output << "goto " << stmt->target;
1064                } else if ( nullptr != stmt->computedTarget ) {
1065                        output << "goto *";
1066                        stmt->computedTarget->accept( *visitor );
1067                }
1068                break;
1069        case ast::BranchStmt::Break:
1070                output << "break";
1071                break;
1072        case ast::BranchStmt::Continue:
1073                output << "continue";
1074                break;
1075        case ast::BranchStmt::FallThrough:
1076        case ast::BranchStmt::FallThroughDefault:
1077                assertf( !options.genC, "fallthru should not reach code generation." );
1078                output << "fallthru";
1079                break;
1080        default:
1081                assertf( false, "Bad BranchStmt value." );
1082        }
1083        // Print branch target for labelled break/continue/fallthru in debug mode.
1084        if ( !options.genC && stmt->kind != ast::BranchStmt::Goto ) {
1085                if ( !stmt->target.empty() ) {
1086                        output << " " << stmt->target;
1087                } else if ( stmt->kind == ast::BranchStmt::FallThrough ) {
1088                        output << " default";
1089                }
1090        }
1091        output << ";";
1092}
1093
1094void CodeGenerator::postvisit( ast::ReturnStmt const * stmt ) {
1095        output << "return ";
1096        if ( stmt->expr ) stmt->expr->accept( *visitor );
1097        output << ";";
1098}
1099
1100void CodeGenerator::postvisit( ast::ThrowStmt const * stmt ) {
1101        assertf( !options.genC, "ThrowStmt should not reach code generation." );
1102
1103        output << ((stmt->kind == ast::Terminate) ? "throw" : "throwResume");
1104        if ( stmt->expr ) {
1105                output << " ";
1106                stmt->expr->accept( *visitor );
1107        }
1108        if ( stmt->target ) {
1109                output << " _At ";
1110                stmt->target->accept( *visitor );
1111        }
1112        output << ";";
1113}
1114
1115void CodeGenerator::postvisit( ast::CatchClause const * stmt ) {
1116        assertf( !options.genC, "CatchClause should not reach code generation." );
1117
1118        output << ((stmt->kind == ast::Terminate) ? "catch" : "catchResume");
1119        output << "( ";
1120        stmt->decl->accept( *visitor );
1121        if ( stmt->cond ) {
1122                output << " ; ";
1123                stmt->cond->accept( *visitor );
1124        }
1125        output << " ) ";
1126        stmt->body->accept( *visitor );
1127}
1128
1129void CodeGenerator::postvisit( ast::WaitForStmt const * stmt ) {
1130        assertf( !options.genC, "WaitforStmt should not reach code generation." );
1131
1132        bool first = true;
1133        for ( ast::ptr<ast::WaitForClause> const & clause : stmt->clauses ) {
1134                if (first) { output << "or "; first = false; }
1135                if ( clause->when_cond ) {
1136                        output << "when(";
1137                        stmt->timeout_cond->accept( *visitor );
1138                        output << ") ";
1139                }
1140                output << "waitfor(";
1141                clause->target->accept( *visitor );
1142                for ( ast::ptr<ast::Expr> const & expr : clause->target_args ) {
1143                        output << ",";
1144                        expr->accept( *visitor );
1145                }
1146                output << ") ";
1147                clause->stmt->accept( *visitor );
1148        }
1149
1150        if ( stmt->timeout_stmt ) {
1151                output << "or ";
1152                if ( stmt->timeout_cond ) {
1153                        output << "when(";
1154                        stmt->timeout_cond->accept( *visitor );
1155                        output << ") ";
1156                }
1157                output << "timeout(";
1158                stmt->timeout_time->accept( *visitor );
1159                output << ") ";
1160                stmt->timeout_stmt->accept( *visitor );
1161        }
1162
1163        if ( stmt->else_stmt ) {
1164                output << "or ";
1165                if ( stmt->else_cond ) {
1166                        output << "when(";
1167                        stmt->else_cond->accept( *visitor );
1168                        output << ")";
1169                }
1170                output << "else ";
1171                stmt->else_stmt->accept( *visitor );
1172        }
1173}
1174
1175void CodeGenerator::postvisit( ast::WithStmt const * stmt ) {
1176        assertf( !options.genC, "WithStmt should not reach code generation." );
1177
1178        output << "with ( ";
1179        genCommaList( stmt->exprs );
1180        output << " ) ";
1181        stmt->stmt->accept( *visitor );
1182}
1183
1184void CodeGenerator::postvisit( ast::WhileDoStmt const * stmt ) {
1185        if ( stmt->isDoWhile ) {
1186                output << "do";
1187        } else {
1188                output << "while (";
1189                stmt->cond->accept( *visitor );
1190                output << ")";
1191        }
1192        output << " ";
1193
1194        output << CodeGenerator::printLabels( stmt->body->labels );
1195        stmt->body->accept( *visitor );
1196
1197        output << indent;
1198
1199        if ( stmt->isDoWhile ) {
1200                output << " while (";
1201                stmt->cond->accept( *visitor );
1202                output << ");";
1203        }
1204}
1205
1206void CodeGenerator::postvisit( ast::ForStmt const * stmt ) {
1207        // Initializer is always hoised so don't generate it.
1208        // TODO: Do an assertion check?
1209        output << "for (;";
1210
1211        if ( nullptr != stmt->cond ) {
1212                stmt->cond->accept( *visitor );
1213        }
1214        output << ";";
1215
1216        if ( nullptr != stmt->inc ) {
1217                // cast the top-level expression to void to reduce gcc warnings.
1218                ast::Expr * expr = new ast::CastExpr( stmt->inc );
1219                expr->accept( *visitor );
1220        }
1221        output << ") ";
1222
1223        if ( nullptr != stmt->body ) {
1224                output << printLabels( stmt->body->labels );
1225                stmt->body->accept( *visitor );
1226        }
1227}
1228
1229void CodeGenerator::postvisit( ast::NullStmt const * ) {
1230        output << "/* null statement */ ;";
1231}
1232
1233void CodeGenerator::postvisit( ast::DeclStmt const * stmt ) {
1234        stmt->decl->accept( *visitor );
1235
1236        if ( doSemicolon( stmt->decl ) ) output << ";";
1237}
1238
1239void CodeGenerator::postvisit( ast::ImplicitCtorDtorStmt const * stmt ) {
1240        assertf( !options.genC, "ImplicitCtorCtorStmt should not reach code generation." );
1241        stmt->callStmt->accept( *visitor );
1242}
1243
1244void CodeGenerator::postvisit( ast::MutexStmt const * stmt ) {
1245        assertf( !options.genC, "MutexStmt should not reach code generation." );
1246        // TODO: But this isn't what a mutex statement looks like.
1247        stmt->stmt->accept( *visitor );
1248}
1249
1250std::string genName( ast::DeclWithType const * decl ) {
1251        if ( const OperatorInfo * opInfo = operatorLookup( decl->name ) ) {
1252                return opInfo->outputName;
1253        } else {
1254                return decl->name;
1255        }
1256}
1257
1258} // namespace CodeGen
Note: See TracBrowser for help on using the repository browser.