source: src/CodeGen/CodeGenerator.cc@ 32fc0d6

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

Fix the missing pieces in codeGen

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