source: src/CodeGen/CodeGenerator.cc@ af75a87

ADT ast-experimental pthread-emulation qualifiedEnum
Last change on this file since af75a87 was 1931bb01, checked in by Andrew Beach <ajbeach@…>, 3 years ago

Converted 'Validate A' to the new AST. There some utility changes as well.

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