source: src/CodeGen/CodeGenerator.cc@ f238fcc2

ADT ast-experimental enum pthread-emulation qualifiedEnum
Last change on this file since f238fcc2 was 3e54399, checked in by JiadaL <j82liang@…>, 4 years ago

The compiler now will add a cast to base type for the usage of type enum; but it will fail because of violating some restrictions for the auto-gen functions. Need to investiage more

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