source: src/CodeGen/CodeGenerator.cc@ 34ed17b

ADT ast-experimental
Last change on this file since 34ed17b was 8bb86ce, checked in by JiadaL <j82liang@…>, 3 years ago

Clean up some code related to Enum codegen

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