source: src/CodeGen/CodeGenerator.cc@ c0c4d4f

ADT ast-experimental enum forall-pointer-decay jacob/cs343-translation new-ast-unique-expr pthread-emulation qualifiedEnum
Last change on this file since c0c4d4f was 2d019af, checked in by Peter A. Buhr <pabuhr@…>, 5 years ago

parser global pragmas, fixes #241

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