source: src/SymTab/Autogen.cc@ 16ba4a6f

ADT arm-eh ast-experimental enum forall-pointer-decay jacob/cs343-translation new-ast-unique-expr pthread-emulation qualifiedEnum
Last change on this file since 16ba4a6f was 16ba4a6f, checked in by Fangren Yu <f37yu@…>, 5 years ago

factor out resolver calls in pre-resolution stage

  • Property mode set to 100644
File size: 34.8 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// Autogen.cc --
8//
9// Author : Rob Schluntz
10// Created On : Thu Mar 03 15:45:56 2016
11// Last Modified By : Peter A. Buhr
12// Last Modified On : Fri Apr 27 14:39:06 2018
13// Update Count : 63
14//
15
16#include "Autogen.h"
17
18#include <algorithm> // for count_if
19#include <cassert> // for strict_dynamic_cast, assert, assertf
20#include <iterator> // for back_insert_iterator, back_inserter
21#include <list> // for list, _List_iterator, list<>::iter...
22#include <set> // for set, _Rb_tree_const_iterator
23#include <utility> // for pair
24#include <vector> // for vector
25
26#include "AST/Decl.hpp"
27#include "CodeGen/OperatorTable.h" // for isCtorDtor, isCtorDtorAssign
28#include "Common/PassVisitor.h" // for PassVisitor
29#include "Common/ScopedMap.h" // for ScopedMap<>::const_iterator, Scope...
30#include "Common/utility.h" // for cloneAll, operator+
31#include "GenPoly/ScopedSet.h" // for ScopedSet, ScopedSet<>::iterator
32#include "InitTweak/GenInit.h" // for fixReturnStatements
33#include "ResolvExpr/Resolver.h" // for resolveDecl
34#include "SymTab/Mangler.h" // for Mangler
35#include "SynTree/Attribute.h" // For Attribute
36#include "SynTree/Mutator.h" // for maybeMutate
37#include "SynTree/Statement.h" // for CompoundStmt, ReturnStmt, ExprStmt
38#include "SynTree/Type.h" // for FunctionType, Type, TypeInstType
39#include "SynTree/Visitor.h" // for maybeAccept, Visitor, acceptAll
40#include "CompilationState.h"
41
42class Attribute;
43
44namespace SymTab {
45 /// Data used to generate functions generically. Specifically, the name of the generated function and a function which generates the routine protoype
46 struct FuncData {
47 typedef FunctionType * (*TypeGen)( Type *, bool );
48 FuncData( const std::string & fname, const TypeGen & genType ) : fname( fname ), genType( genType ) {}
49 std::string fname;
50 TypeGen genType;
51 };
52
53 struct AutogenerateRoutines final : public WithDeclsToAdd, public WithVisitorRef<AutogenerateRoutines>, public WithGuards, public WithShortCircuiting, public WithIndexer {
54 AutogenerateRoutines();
55
56 void previsit( EnumDecl * enumDecl );
57 void previsit( StructDecl * structDecl );
58 void previsit( UnionDecl * structDecl );
59 void previsit( TypeDecl * typeDecl );
60 void previsit( TraitDecl * traitDecl );
61 void previsit( FunctionDecl * functionDecl );
62
63 void previsit( CompoundStmt * compoundStmt );
64
65 private:
66
67 GenPoly::ScopedSet< std::string > structsDone;
68 unsigned int functionNesting = 0; // current level of nested functions
69
70 std::vector< FuncData > data;
71 };
72
73 /// generates routines for tuple types.
74 struct AutogenTupleRoutines : public WithDeclsToAdd, public WithVisitorRef<AutogenTupleRoutines>, public WithGuards, public WithShortCircuiting {
75 void previsit( FunctionDecl * functionDecl );
76
77 void postvisit( TupleType * tupleType );
78
79 void previsit( CompoundStmt * compoundStmt );
80
81 private:
82 unsigned int functionNesting = 0; // current level of nested functions
83 GenPoly::ScopedSet< std::string > seenTuples;
84 };
85
86 void autogenerateRoutines( std::list< Declaration * > &translationUnit ) {
87 PassVisitor<AutogenerateRoutines> generator;
88 acceptAll( translationUnit, generator );
89
90 // needs to be done separately because AutogenerateRoutines skips types that appear as function arguments, etc.
91 // AutogenTupleRoutines tupleGenerator;
92 // acceptAll( translationUnit, tupleGenerator );
93 }
94
95 //=============================================================================================
96 // FuncGenerator definitions
97 //=============================================================================================
98 class FuncGenerator {
99 public:
100 std::list< Declaration * > definitions, forwards;
101
102 FuncGenerator( Type * type, const std::vector< FuncData > & data, unsigned int functionNesting, SymTab::Indexer & indexer ) : type( type ), data( data ), functionNesting( functionNesting ), indexer( indexer ) {}
103
104 virtual bool shouldAutogen() const = 0;
105 void genStandardFuncs();
106 virtual void genFieldCtors() = 0;
107 protected:
108 Type * type;
109 const std::vector< FuncData > & data;
110 unsigned int functionNesting;
111 SymTab::Indexer & indexer;
112
113 virtual void genFuncBody( FunctionDecl * dcl ) = 0;
114 virtual bool isConcurrentType() const = 0;
115
116 void resolve( FunctionDecl * dcl );
117 void generatePrototypes( std::list< FunctionDecl * > & newFuncs );
118 };
119
120 class StructFuncGenerator : public FuncGenerator {
121 StructDecl * aggregateDecl;
122 public:
123 StructFuncGenerator( StructDecl * aggregateDecl, StructInstType * refType, const std::vector< FuncData > & data, unsigned int functionNesting, SymTab::Indexer & indexer ) : FuncGenerator( refType, data, functionNesting, indexer ), aggregateDecl( aggregateDecl) {}
124
125 virtual bool shouldAutogen() const override;
126 virtual bool isConcurrentType() const override;
127
128 virtual void genFuncBody( FunctionDecl * dcl ) override;
129 virtual void genFieldCtors() override;
130
131 private:
132 /// generates a single struct member operation (constructor call, destructor call, assignment call)
133 void makeMemberOp( ObjectDecl * dstParam, Expression * src, DeclarationWithType * field, FunctionDecl * func, bool forward = true );
134
135 /// generates the body of a struct function by iterating the struct members (via parameters) - generates default ctor, copy ctor, assignment, and dtor bodies, but NOT field ctor bodies
136 template<typename Iterator>
137 void makeFunctionBody( Iterator member, Iterator end, FunctionDecl * func, bool forward = true );
138
139 /// generate the body of a constructor which takes parameters that match fields, e.g.
140 /// void ?{}(A *, int) and void?{}(A *, int, int) for a struct A which has two int fields.
141 template<typename Iterator>
142 void makeFieldCtorBody( Iterator member, Iterator end, FunctionDecl * func );
143 };
144
145 class UnionFuncGenerator : public FuncGenerator {
146 UnionDecl * aggregateDecl;
147 public:
148 UnionFuncGenerator( UnionDecl * aggregateDecl, UnionInstType * refType, const std::vector< FuncData > & data, unsigned int functionNesting, SymTab::Indexer & indexer ) : FuncGenerator( refType, data, functionNesting, indexer ), aggregateDecl( aggregateDecl) {}
149
150 virtual bool shouldAutogen() const override;
151 virtual bool isConcurrentType() const override;
152
153 virtual void genFuncBody( FunctionDecl * dcl ) override;
154 virtual void genFieldCtors() override;
155
156 private:
157 /// generates a single struct member operation (constructor call, destructor call, assignment call)
158 template<typename OutputIterator>
159 void makeMemberOp( ObjectDecl * srcParam, ObjectDecl * dstParam, OutputIterator out );
160
161 /// generates the body of a struct function by iterating the struct members (via parameters) - generates default ctor, copy ctor, assignment, and dtor bodies, but NOT field ctor bodies
162 template<typename Iterator>
163 void makeFunctionBody( Iterator member, Iterator end, FunctionDecl * func, bool forward = true );
164
165 /// generate the body of a constructor which takes parameters that match fields, e.g.
166 /// void ?{}(A *, int) and void?{}(A *, int, int) for a struct A which has two int fields.
167 template<typename Iterator>
168 void makeFieldCtorBody( Iterator member, Iterator end, FunctionDecl * func );
169 };
170
171 class EnumFuncGenerator : public FuncGenerator {
172 public:
173 EnumFuncGenerator( EnumInstType * refType, const std::vector< FuncData > & data, unsigned int functionNesting, SymTab::Indexer & indexer ) : FuncGenerator( refType, data, functionNesting, indexer ) {}
174
175 virtual bool shouldAutogen() const override;
176 virtual bool isConcurrentType() const override;
177
178 virtual void genFuncBody( FunctionDecl * dcl ) override;
179 virtual void genFieldCtors() override;
180
181 private:
182 };
183
184 class TypeFuncGenerator : public FuncGenerator {
185 TypeDecl * typeDecl;
186 public:
187 TypeFuncGenerator( TypeDecl * typeDecl, TypeInstType * refType, const std::vector<FuncData> & data, unsigned int functionNesting, SymTab::Indexer & indexer ) : FuncGenerator( refType, data, functionNesting, indexer ), typeDecl( typeDecl ) {}
188
189 virtual bool shouldAutogen() const override;
190 virtual void genFuncBody( FunctionDecl * dcl ) override;
191 virtual bool isConcurrentType() const override;
192 virtual void genFieldCtors() override;
193 };
194
195 //=============================================================================================
196 // helper functions
197 //=============================================================================================
198 void generateFunctions( FuncGenerator & gen, std::list< Declaration * > & declsToAdd ) {
199 if ( ! gen.shouldAutogen() ) return;
200
201 // generate each of the functions based on the supplied FuncData objects
202 gen.genStandardFuncs();
203 gen.genFieldCtors();
204
205 declsToAdd.splice( declsToAdd.end(), gen.forwards );
206 declsToAdd.splice( declsToAdd.end(), gen.definitions );
207 }
208
209 bool isUnnamedBitfield( ObjectDecl * obj ) {
210 return obj != nullptr && obj->name == "" && obj->bitfieldWidth != nullptr;
211 }
212
213 bool isUnnamedBitfield( const ast::ObjectDecl * obj ) {
214 return obj && obj->name.empty() && obj->bitfieldWidth;
215 }
216
217 /// inserts a forward declaration for functionDecl into declsToAdd
218 void addForwardDecl( FunctionDecl * functionDecl, std::list< Declaration * > & declsToAdd ) {
219 FunctionDecl * decl = functionDecl->clone();
220 delete decl->statements;
221 decl->statements = nullptr;
222 declsToAdd.push_back( decl );
223 decl->fixUniqueId();
224 }
225
226 const std::list< TypeDecl * > getGenericParams( Type * t ) {
227 std::list< TypeDecl * > * ret = nullptr;
228 if ( StructInstType * inst = dynamic_cast< StructInstType * > ( t ) ) {
229 ret = inst->get_baseParameters();
230 } else if ( UnionInstType * inst = dynamic_cast< UnionInstType * >( t ) ) {
231 ret = inst->get_baseParameters();
232 }
233 return ret ? *ret : std::list< TypeDecl * >();
234 }
235
236 // shallow copy the pointer list for return
237 std::vector<ast::ptr<ast::TypeDecl>> getGenericParams (const ast::Type * t) {
238 if (auto structInst = dynamic_cast<const ast::StructInstType*>(t)) {
239 return structInst->base->params;
240 }
241 if (auto unionInst = dynamic_cast<const ast::UnionInstType*>(t)) {
242 return unionInst->base->params;
243 }
244 return {};
245 }
246
247 /// given type T, generate type of default ctor/dtor, i.e. function type void (*) (T *)
248 FunctionType * genDefaultType( Type * paramType, bool maybePolymorphic ) {
249 FunctionType *ftype = new FunctionType( Type::Qualifiers(), false );
250 if ( maybePolymorphic ) {
251 // only copy in
252 const auto & typeParams = getGenericParams( paramType );
253 cloneAll( typeParams, ftype->forall );
254 }
255 ObjectDecl *dstParam = new ObjectDecl( "_dst", Type::StorageClasses(), LinkageSpec::Cforall, nullptr, new ReferenceType( Type::Qualifiers(), paramType->clone() ), nullptr );
256 ftype->parameters.push_back( dstParam );
257 return ftype;
258 }
259
260 ///
261 ast::FunctionDecl * genDefaultFunc(const CodeLocation loc, const std::string fname, const ast::Type * paramType, bool maybePolymorphic) {
262 std::vector<ast::ptr<ast::TypeDecl>> typeParams;
263 if (maybePolymorphic) typeParams = getGenericParams(paramType);
264 auto dstParam = new ast::ObjectDecl(loc, "_dst", new ast::ReferenceType(paramType), nullptr, {}, ast::Linkage::Cforall);
265 return new ast::FunctionDecl(loc, fname, std::move(typeParams), {dstParam}, {}, new ast::CompoundStmt(loc));
266 }
267
268 /// given type T, generate type of copy ctor, i.e. function type void (*) (T *, T)
269 FunctionType * genCopyType( Type * paramType, bool maybePolymorphic ) {
270 FunctionType *ftype = genDefaultType( paramType, maybePolymorphic );
271 ObjectDecl *srcParam = new ObjectDecl( "_src", Type::StorageClasses(), LinkageSpec::Cforall, nullptr, paramType->clone(), nullptr );
272 ftype->parameters.push_back( srcParam );
273 return ftype;
274 }
275
276 /// given type T, generate type of assignment, i.e. function type T (*) (T *, T)
277 FunctionType * genAssignType( Type * paramType, bool maybePolymorphic ) {
278 FunctionType *ftype = genCopyType( paramType, maybePolymorphic );
279 ObjectDecl *returnVal = new ObjectDecl( "_ret", Type::StorageClasses(), LinkageSpec::Cforall, nullptr, paramType->clone(), nullptr );
280 ftype->returnVals.push_back( returnVal );
281 return ftype;
282 }
283
284 /// generate a function decl from a name and type. Nesting depth determines whether
285 /// the declaration is static or not; optional paramter determines if declaration is intrinsic
286 FunctionDecl * genFunc( const std::string & fname, FunctionType * ftype, unsigned int functionNesting, bool isIntrinsic = false ) {
287 // Routines at global scope marked "static" to prevent multiple definitions in separate translation units
288 // because each unit generates copies of the default routines for each aggregate.
289 Type::StorageClasses scs = functionNesting > 0 ? Type::StorageClasses() : Type::StorageClasses( Type::Static );
290 LinkageSpec::Spec spec = isIntrinsic ? LinkageSpec::Intrinsic : LinkageSpec::AutoGen;
291 FunctionDecl * decl = new FunctionDecl( fname, scs, spec, ftype, new CompoundStmt(),
292 std::list< Attribute * >(), Type::FuncSpecifiers( Type::Inline ) );
293 decl->fixUniqueId();
294 return decl;
295 }
296
297 Type * declToType( Declaration * decl ) {
298 if ( DeclarationWithType * dwt = dynamic_cast< DeclarationWithType * >( decl ) ) {
299 return dwt->get_type();
300 }
301 return nullptr;
302 }
303
304 Type * declToTypeDeclBase( Declaration * decl ) {
305 if ( TypeDecl * td = dynamic_cast< TypeDecl * >( decl ) ) {
306 return td->base;
307 }
308 return nullptr;
309 }
310
311 //=============================================================================================
312 // FuncGenerator member definitions
313 //=============================================================================================
314 void FuncGenerator::genStandardFuncs() {
315 std::list< FunctionDecl * > newFuncs;
316 generatePrototypes( newFuncs );
317
318 for ( FunctionDecl * dcl : newFuncs ) {
319 genFuncBody( dcl );
320 if ( CodeGen::isAssignment( dcl->name ) ) {
321 // assignment needs to return a value
322 FunctionType * assignType = dcl->type;
323 assert( assignType->parameters.size() == 2 );
324 assert( assignType->returnVals.size() == 1 );
325 ObjectDecl * dstParam = strict_dynamic_cast< ObjectDecl * >( assignType->parameters.front() );
326 dcl->statements->push_back( new ReturnStmt( new VariableExpr( dstParam ) ) );
327 }
328 resolve( dcl );
329 }
330 }
331
332 void FuncGenerator::generatePrototypes( std::list< FunctionDecl * > & newFuncs ) {
333 bool concurrent_type = isConcurrentType();
334 for ( const FuncData & d : data ) {
335 // generate a function (?{}, ?=?, ^?{}) based on the current FuncData.
336 FunctionType * ftype = d.genType( type, true );
337
338 // destructor for concurrent type must be mutex
339 if ( concurrent_type && CodeGen::isDestructor( d.fname ) ) {
340 ftype->parameters.front()->get_type()->set_mutex( true );
341 }
342
343 newFuncs.push_back( genFunc( d.fname, ftype, functionNesting ) );
344 }
345 }
346
347 void FuncGenerator::resolve( FunctionDecl * dcl ) {
348 try {
349 ResolvExpr::resolveDecl( dcl, indexer );
350 if ( functionNesting == 0 ) {
351 // forward declare if top-level struct, so that
352 // type is complete as soon as its body ends
353 // Note: this is necessary if we want structs which contain
354 // generic (otype) structs as members.
355 addForwardDecl( dcl, forwards );
356 }
357 definitions.push_back( dcl );
358 indexer.addId( dcl );
359 } catch ( SemanticErrorException & ) {
360 // okay if decl does not resolve - that means the function should not be generated
361 // delete dcl;
362 delete dcl->statements;
363 dcl->statements = nullptr;
364 dcl->isDeleted = true;
365 definitions.push_back( dcl );
366 indexer.addId( dcl );
367 }
368 }
369
370 bool StructFuncGenerator::shouldAutogen() const {
371 // Builtins do not use autogeneration.
372 return ! aggregateDecl->linkage.is_builtin;
373 }
374 bool StructFuncGenerator::isConcurrentType() const { return aggregateDecl->is_thread() || aggregateDecl->is_monitor(); }
375
376 void StructFuncGenerator::genFuncBody( FunctionDecl * dcl ) {
377 // generate appropriate calls to member ctor, assignment
378 // destructor needs to do everything in reverse, so pass "forward" based on whether the function is a destructor
379 if ( ! CodeGen::isDestructor( dcl->name ) ) {
380 makeFunctionBody( aggregateDecl->members.begin(), aggregateDecl->members.end(), dcl );
381 } else {
382 makeFunctionBody( aggregateDecl->members.rbegin(), aggregateDecl->members.rend(), dcl, false );
383 }
384 }
385
386 void StructFuncGenerator::genFieldCtors() {
387 // field ctors are only generated if default constructor and copy constructor are both generated
388 unsigned numCtors = std::count_if( definitions.begin(), definitions.end(), [](Declaration * dcl) { return CodeGen::isConstructor( dcl->name ); } );
389
390 // Field constructors are only generated if default and copy constructor
391 // are generated, since they need access to both
392 if ( numCtors != 2 ) return;
393
394 // create constructors which take each member type as a parameter.
395 // for example, for struct A { int x, y; }; generate
396 // void ?{}(A *, int) and void ?{}(A *, int, int)
397 FunctionType * memCtorType = genDefaultType( type );
398 for ( Declaration * member : aggregateDecl->members ) {
399 DeclarationWithType * field = strict_dynamic_cast<DeclarationWithType *>( member );
400 if ( isUnnamedBitfield( dynamic_cast< ObjectDecl * > ( field ) ) ) {
401 // don't make a function whose parameter is an unnamed bitfield
402 continue;
403 }
404 // do not carry over field's attributes to parameter type
405 Type * paramType = field->get_type()->clone();
406 deleteAll( paramType->attributes );
407 paramType->attributes.clear();
408 // add a parameter corresponding to this field
409 ObjectDecl * param = new ObjectDecl( field->name, Type::StorageClasses(), LinkageSpec::Cforall, nullptr, paramType, nullptr );
410 cloneAll_if( field->attributes, param->attributes, [](Attribute * attr) { return attr->isValidOnFuncParam(); } );
411 memCtorType->parameters.push_back( param );
412 FunctionDecl * ctor = genFunc( "?{}", memCtorType->clone(), functionNesting );
413 makeFieldCtorBody( aggregateDecl->members.begin(), aggregateDecl->members.end(), ctor );
414 resolve( ctor );
415 }
416 delete memCtorType;
417 }
418
419 void StructFuncGenerator::makeMemberOp( ObjectDecl * dstParam, Expression * src, DeclarationWithType * field, FunctionDecl * func, bool forward ) {
420 InitTweak::InitExpander_old srcParam( src );
421
422 // assign to destination
423 Expression *dstselect = new MemberExpr( field, new CastExpr( new VariableExpr( dstParam ), strict_dynamic_cast< ReferenceType* >( dstParam->get_type() )->base->clone() ) );
424 genImplicitCall( srcParam, dstselect, func->name, back_inserter( func->statements->kids ), field, forward );
425 }
426
427 template<typename Iterator>
428 void StructFuncGenerator::makeFunctionBody( Iterator member, Iterator end, FunctionDecl * func, bool forward ) {
429 for ( ; member != end; ++member ) {
430 if ( DeclarationWithType *field = dynamic_cast< DeclarationWithType * >( *member ) ) { // otherwise some form of type declaration, e.g. Aggregate
431 // query the type qualifiers of this field and skip assigning it if it is marked const.
432 // If it is an array type, we need to strip off the array layers to find its qualifiers.
433 Type * type = field->get_type();
434 while ( ArrayType * at = dynamic_cast< ArrayType * >( type ) ) {
435 type = at->get_base();
436 }
437
438 if ( type->get_const() && CodeGen::isAssignment( func->name ) ) {
439 // don't assign const members, but do construct/destruct
440 continue;
441 }
442
443 assert( ! func->get_functionType()->get_parameters().empty() );
444 ObjectDecl * dstParam = dynamic_cast<ObjectDecl*>( func->get_functionType()->get_parameters().front() );
445 ObjectDecl * srcParam = nullptr;
446 if ( func->get_functionType()->get_parameters().size() == 2 ) {
447 srcParam = dynamic_cast<ObjectDecl*>( func->get_functionType()->get_parameters().back() );
448 }
449
450 // srcParam may be NULL, in which case we have default ctor/dtor
451 assert( dstParam );
452
453 Expression *srcselect = srcParam ? new MemberExpr( field, new VariableExpr( srcParam ) ) : nullptr;
454 makeMemberOp( dstParam, srcselect, field, func, forward );
455 } // if
456 } // for
457 } // makeFunctionBody
458
459 template<typename Iterator>
460 void StructFuncGenerator::makeFieldCtorBody( Iterator member, Iterator end, FunctionDecl * func ) {
461 FunctionType * ftype = func->type;
462 std::list<DeclarationWithType*> & params = ftype->parameters;
463 assert( params.size() >= 2 ); // should not call this function for default ctor, etc.
464
465 // skip 'this' parameter
466 ObjectDecl * dstParam = dynamic_cast<ObjectDecl*>( params.front() );
467 assert( dstParam );
468 std::list<DeclarationWithType*>::iterator parameter = params.begin()+1;
469 for ( ; member != end; ++member ) {
470 if ( DeclarationWithType * field = dynamic_cast<DeclarationWithType*>( *member ) ) {
471 if ( isUnnamedBitfield( dynamic_cast< ObjectDecl * > ( field ) ) ) {
472 // don't make a function whose parameter is an unnamed bitfield
473 continue;
474 } else if ( parameter != params.end() ) {
475 // matching parameter, initialize field with copy ctor
476 Expression *srcselect = new VariableExpr(*parameter);
477 makeMemberOp( dstParam, srcselect, field, func );
478 ++parameter;
479 } else {
480 // no matching parameter, initialize field with default ctor
481 makeMemberOp( dstParam, nullptr, field, func );
482 }
483 }
484 }
485 }
486
487 bool UnionFuncGenerator::shouldAutogen() const {
488 // Builtins do not use autogeneration.
489 return ! aggregateDecl->linkage.is_builtin;
490 }
491
492 // xxx - is this right?
493 bool UnionFuncGenerator::isConcurrentType() const { return false; };
494
495 /// generate a single union assignment expression (using memcpy)
496 template< typename OutputIterator >
497 void UnionFuncGenerator::makeMemberOp( ObjectDecl * srcParam, ObjectDecl * dstParam, OutputIterator out ) {
498 UntypedExpr *copy = new UntypedExpr( new NameExpr( "__builtin_memcpy" ) );
499 copy->args.push_back( new AddressExpr( new VariableExpr( dstParam ) ) );
500 copy->args.push_back( new AddressExpr( new VariableExpr( srcParam ) ) );
501 copy->args.push_back( new SizeofExpr( srcParam->get_type()->clone() ) );
502 *out++ = new ExprStmt( copy );
503 }
504
505 /// generates the body of a union assignment/copy constructor/field constructor
506 void UnionFuncGenerator::genFuncBody( FunctionDecl * funcDecl ) {
507 FunctionType * ftype = funcDecl->type;
508 if ( InitTweak::isCopyConstructor( funcDecl ) || InitTweak::isAssignment( funcDecl ) ) {
509 assert( ftype->parameters.size() == 2 );
510 ObjectDecl * dstParam = strict_dynamic_cast< ObjectDecl * >( ftype->parameters.front() );
511 ObjectDecl * srcParam = strict_dynamic_cast< ObjectDecl * >( ftype->parameters.back() );
512 makeMemberOp( srcParam, dstParam, back_inserter( funcDecl->statements->kids ) );
513 } else {
514 // default ctor/dtor body is empty - add unused attribute to parameter to silence warnings
515 assert( ftype->parameters.size() == 1 );
516 ObjectDecl * dstParam = strict_dynamic_cast< ObjectDecl * >( ftype->parameters.front() );
517 dstParam->attributes.push_back( new Attribute( "unused" ) );
518 }
519 }
520
521 /// generate the body of a constructor which takes parameters that match fields, e.g.
522 /// void ?{}(A *, int) and void?{}(A *, int, int) for a struct A which has two int fields.
523 void UnionFuncGenerator::genFieldCtors() {
524 // field ctors are only generated if default constructor and copy constructor are both generated
525 unsigned numCtors = std::count_if( definitions.begin(), definitions.end(), [](Declaration * dcl) { return CodeGen::isConstructor( dcl->get_name() ); } );
526
527 // Field constructors are only generated if default and copy constructor
528 // are generated, since they need access to both
529 if ( numCtors != 2 ) return;
530
531 // create a constructor which takes the first member type as a parameter.
532 // for example, for Union A { int x; double y; }; generate
533 // void ?{}(A *, int)
534 // This is to mimic C's behaviour which initializes the first member of the union.
535 FunctionType * memCtorType = genDefaultType( type );
536 for ( Declaration * member : aggregateDecl->members ) {
537 DeclarationWithType * field = strict_dynamic_cast<DeclarationWithType *>( member );
538 if ( isUnnamedBitfield( dynamic_cast< ObjectDecl * > ( field ) ) ) {
539 // don't make a function whose parameter is an unnamed bitfield
540 break;
541 }
542 // do not carry over field's attributes to parameter type
543 Type * paramType = field->get_type()->clone();
544 deleteAll( paramType->attributes );
545 paramType->attributes.clear();
546 // add a parameter corresponding to this field
547 memCtorType->parameters.push_back( new ObjectDecl( field->name, Type::StorageClasses(), LinkageSpec::Cforall, nullptr, paramType, nullptr ) );
548 FunctionDecl * ctor = genFunc( "?{}", memCtorType->clone(), functionNesting );
549 ObjectDecl * srcParam = strict_dynamic_cast<ObjectDecl *>( ctor->type->parameters.back() );
550 srcParam->fixUniqueId();
551 ObjectDecl * dstParam = InitTweak::getParamThis( ctor->type );
552 makeMemberOp( srcParam, dstParam, back_inserter( ctor->statements->kids ) );
553 resolve( ctor );
554 // only generate one field ctor for unions
555 break;
556 }
557 delete memCtorType;
558 }
559
560 void EnumFuncGenerator::genFuncBody( FunctionDecl * funcDecl ) {
561 // xxx - Temporary: make these functions intrinsic so they codegen as C assignment.
562 // Really they're something of a cross between instrinsic and autogen, so should
563 // probably make a new linkage type
564 funcDecl->linkage = LinkageSpec::Intrinsic;
565 FunctionType * ftype = funcDecl->type;
566 if ( InitTweak::isCopyConstructor( funcDecl ) || InitTweak::isAssignment( funcDecl ) ) {
567 assert( ftype->parameters.size() == 2 );
568 ObjectDecl * dstParam = strict_dynamic_cast< ObjectDecl * >( ftype->parameters.front() );
569 ObjectDecl * srcParam = strict_dynamic_cast< ObjectDecl * >( ftype->parameters.back() );
570
571 // enum copy construct and assignment is just C-style assignment.
572 // this looks like a bad recursive call, but code gen will turn it into
573 // a C-style assignment.
574 // This happens before function pointer type conversion, so need to do it manually here
575 ApplicationExpr * callExpr = new ApplicationExpr( VariableExpr::functionPointer( funcDecl ) );
576 callExpr->get_args().push_back( new VariableExpr( dstParam ) );
577 callExpr->get_args().push_back( new VariableExpr( srcParam ) );
578 funcDecl->statements->push_back( new ExprStmt( callExpr ) );
579 } else {
580 // default ctor/dtor body is empty - add unused attribute to parameter to silence warnings
581 assert( ftype->parameters.size() == 1 );
582 ObjectDecl * dstParam = strict_dynamic_cast< ObjectDecl * >( ftype->parameters.front() );
583 dstParam->attributes.push_back( new Attribute( "unused" ) );
584 }
585 }
586
587 bool EnumFuncGenerator::shouldAutogen() const { return true; }
588 bool EnumFuncGenerator::isConcurrentType() const { return false; }
589 // enums do not have field constructors
590 void EnumFuncGenerator::genFieldCtors() {}
591
592 bool TypeFuncGenerator::shouldAutogen() const { return true; };
593
594 void TypeFuncGenerator::genFuncBody( FunctionDecl * dcl ) {
595 FunctionType * ftype = dcl->type;
596 assertf( ftype->parameters.size() == 1 || ftype->parameters.size() == 2, "Incorrect number of parameters in autogenerated typedecl function: %zd", ftype->parameters.size() );
597 DeclarationWithType * dst = ftype->parameters.front();
598 DeclarationWithType * src = ftype->parameters.size() == 2 ? ftype->parameters.back() : nullptr;
599 // generate appropriate calls to member ctor, assignment
600 UntypedExpr * expr = new UntypedExpr( new NameExpr( dcl->name ) );
601 expr->args.push_back( new CastExpr( new VariableExpr( dst ), new ReferenceType( Type::Qualifiers(), typeDecl->base->clone() ) ) );
602 if ( src ) expr->args.push_back( new CastExpr( new VariableExpr( src ), typeDecl->base->clone() ) );
603 dcl->statements->kids.push_back( new ExprStmt( expr ) );
604 };
605
606 // xxx - should reach in and determine if base type is concurrent?
607 bool TypeFuncGenerator::isConcurrentType() const { return false; };
608
609 // opaque types do not have field constructors
610 void TypeFuncGenerator::genFieldCtors() {};
611
612 //=============================================================================================
613 // Visitor definitions
614 //=============================================================================================
615 AutogenerateRoutines::AutogenerateRoutines() {
616 // the order here determines the order that these functions are generated.
617 // assignment should come last since it uses copy constructor in return.
618 data.emplace_back( "?{}", genDefaultType );
619 data.emplace_back( "?{}", genCopyType );
620 data.emplace_back( "^?{}", genDefaultType );
621 data.emplace_back( "?=?", genAssignType );
622 }
623
624 void AutogenerateRoutines::previsit( EnumDecl * enumDecl ) {
625 // must visit children (enum constants) to add them to the indexer
626 if ( enumDecl->has_body() ) {
627 EnumInstType enumInst( Type::Qualifiers(), enumDecl->get_name() );
628 enumInst.set_baseEnum( enumDecl );
629 EnumFuncGenerator gen( &enumInst, data, functionNesting, indexer );
630 generateFunctions( gen, declsToAddAfter );
631 }
632 }
633
634 void AutogenerateRoutines::previsit( StructDecl * structDecl ) {
635 visit_children = false;
636 if ( structDecl->has_body() ) {
637 StructInstType structInst( Type::Qualifiers(), structDecl->name );
638 structInst.set_baseStruct( structDecl );
639 for ( TypeDecl * typeDecl : structDecl->parameters ) {
640 structInst.parameters.push_back( new TypeExpr( new TypeInstType( Type::Qualifiers(), typeDecl->name, typeDecl ) ) );
641 }
642 StructFuncGenerator gen( structDecl, &structInst, data, functionNesting, indexer );
643 generateFunctions( gen, declsToAddAfter );
644 } // if
645 }
646
647 void AutogenerateRoutines::previsit( UnionDecl * unionDecl ) {
648 visit_children = false;
649 if ( unionDecl->has_body() ) {
650 UnionInstType unionInst( Type::Qualifiers(), unionDecl->get_name() );
651 unionInst.set_baseUnion( unionDecl );
652 for ( TypeDecl * typeDecl : unionDecl->get_parameters() ) {
653 unionInst.get_parameters().push_back( new TypeExpr( new TypeInstType( Type::Qualifiers(), typeDecl->get_name(), typeDecl ) ) );
654 }
655 UnionFuncGenerator gen( unionDecl, &unionInst, data, functionNesting, indexer );
656 generateFunctions( gen, declsToAddAfter );
657 } // if
658 }
659
660 // generate ctor/dtors/assign for typedecls, e.g., otype T = int *;
661 void AutogenerateRoutines::previsit( TypeDecl * typeDecl ) {
662 if ( ! typeDecl->base ) return;
663
664 TypeInstType refType( Type::Qualifiers(), typeDecl->name, typeDecl );
665 TypeFuncGenerator gen( typeDecl, &refType, data, functionNesting, indexer );
666 generateFunctions( gen, declsToAddAfter );
667
668 }
669
670 void AutogenerateRoutines::previsit( TraitDecl * ) {
671 // ensure that we don't add assignment ops for types defined as part of the trait
672 visit_children = false;
673 }
674
675 void AutogenerateRoutines::previsit( FunctionDecl * ) {
676 // Track whether we're currently in a function.
677 // Can ignore function type idiosyncrasies, because function type can never
678 // declare a new type.
679 functionNesting += 1;
680 GuardAction( [this]() { functionNesting -= 1; } );
681 }
682
683 void AutogenerateRoutines::previsit( CompoundStmt * ) {
684 GuardScope( structsDone );
685 }
686
687 void makeTupleFunctionBody( FunctionDecl * function ) {
688 FunctionType * ftype = function->get_functionType();
689 assertf( ftype->get_parameters().size() == 1 || ftype->get_parameters().size() == 2, "too many parameters in generated tuple function" );
690
691 UntypedExpr * untyped = new UntypedExpr( new NameExpr( function->get_name() ) );
692
693 /// xxx - &* is used to make this easier for later passes to handle
694 untyped->get_args().push_back( new AddressExpr( UntypedExpr::createDeref( new VariableExpr( ftype->get_parameters().front() ) ) ) );
695 if ( ftype->get_parameters().size() == 2 ) {
696 untyped->get_args().push_back( new VariableExpr( ftype->get_parameters().back() ) );
697 }
698 function->get_statements()->get_kids().push_back( new ExprStmt( untyped ) );
699 function->get_statements()->get_kids().push_back( new ReturnStmt( UntypedExpr::createDeref( new VariableExpr( ftype->get_parameters().front() ) ) ) );
700 }
701
702 void AutogenTupleRoutines::postvisit( TupleType * tupleType ) {
703 std::string mangleName = SymTab::Mangler::mangleType( tupleType );
704 if ( seenTuples.find( mangleName ) != seenTuples.end() ) return;
705 seenTuples.insert( mangleName );
706
707 // T ?=?(T *, T);
708 FunctionType *assignType = genAssignType( tupleType );
709
710 // void ?{}(T *); void ^?{}(T *);
711 FunctionType *ctorType = genDefaultType( tupleType );
712 FunctionType *dtorType = genDefaultType( tupleType );
713
714 // void ?{}(T *, T);
715 FunctionType *copyCtorType = genCopyType( tupleType );
716
717 std::set< TypeDecl* > done;
718 std::list< TypeDecl * > typeParams;
719 for ( Type * t : *tupleType ) {
720 if ( TypeInstType * ty = dynamic_cast< TypeInstType * >( t ) ) {
721 if ( ! done.count( ty->get_baseType() ) ) {
722 TypeDecl * newDecl = new TypeDecl( ty->get_baseType()->get_name(), Type::StorageClasses(), nullptr, TypeDecl::Dtype, true );
723 TypeInstType * inst = new TypeInstType( Type::Qualifiers(), newDecl->get_name(), newDecl );
724 newDecl->get_assertions().push_back( new FunctionDecl( "?=?", Type::StorageClasses(), LinkageSpec::Cforall, genAssignType( inst ), nullptr,
725 std::list< Attribute * >(), Type::FuncSpecifiers( Type::Inline ) ) );
726 newDecl->get_assertions().push_back( new FunctionDecl( "?{}", Type::StorageClasses(), LinkageSpec::Cforall, genDefaultType( inst ), nullptr,
727 std::list< Attribute * >(), Type::FuncSpecifiers( Type::Inline ) ) );
728 newDecl->get_assertions().push_back( new FunctionDecl( "?{}", Type::StorageClasses(), LinkageSpec::Cforall, genCopyType( inst ), nullptr,
729 std::list< Attribute * >(), Type::FuncSpecifiers( Type::Inline ) ) );
730 newDecl->get_assertions().push_back( new FunctionDecl( "^?{}", Type::StorageClasses(), LinkageSpec::Cforall, genDefaultType( inst ), nullptr,
731 std::list< Attribute * >(), Type::FuncSpecifiers( Type::Inline ) ) );
732 typeParams.push_back( newDecl );
733 done.insert( ty->get_baseType() );
734 }
735 }
736 }
737 cloneAll( typeParams, ctorType->get_forall() );
738 cloneAll( typeParams, dtorType->get_forall() );
739 cloneAll( typeParams, copyCtorType->get_forall() );
740 cloneAll( typeParams, assignType->get_forall() );
741
742 FunctionDecl *assignDecl = genFunc( "?=?", assignType, functionNesting );
743 FunctionDecl *ctorDecl = genFunc( "?{}", ctorType, functionNesting );
744 FunctionDecl *copyCtorDecl = genFunc( "?{}", copyCtorType, functionNesting );
745 FunctionDecl *dtorDecl = genFunc( "^?{}", dtorType, functionNesting );
746
747 makeTupleFunctionBody( assignDecl );
748 makeTupleFunctionBody( ctorDecl );
749 makeTupleFunctionBody( copyCtorDecl );
750 makeTupleFunctionBody( dtorDecl );
751
752 declsToAddBefore.push_back( ctorDecl );
753 declsToAddBefore.push_back( copyCtorDecl );
754 declsToAddBefore.push_back( dtorDecl );
755 declsToAddBefore.push_back( assignDecl ); // assignment should come last since it uses copy constructor in return
756 }
757
758 void AutogenTupleRoutines::previsit( FunctionDecl *functionDecl ) {
759 visit_children = false;
760 maybeAccept( functionDecl->type, *visitor );
761 functionNesting += 1;
762 maybeAccept( functionDecl->statements, *visitor );
763 functionNesting -= 1;
764 }
765
766 void AutogenTupleRoutines::previsit( CompoundStmt * ) {
767 GuardScope( seenTuples );
768 }
769} // SymTab
770
771// Local Variables: //
772// tab-width: 4 //
773// mode: c++ //
774// compile-command: "make install" //
775// End: //
Note: See TracBrowser for help on using the repository browser.