source: src/CodeGen/CodeGenerator.cc@ b787cad

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

Merge with master

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