source: src/CodeGen/CodeGenerator.cc@ 5157ba7

ADT arm-eh ast-experimental cleanup-dtors enum forall-pointer-decay jacob/cs343-translation jenkins-sandbox new-ast new-ast-unique-expr pthread-emulation qualifiedEnum
Last change on this file since 5157ba7 was 42a36d9, checked in by Andrew Beach <ajbeach@…>, 6 years ago

Created CodeGen::Options which hold some flags for code generation.

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