source: src/SymTab/Autogen.cc@ eff03a94

new-env
Last change on this file since eff03a94 was ff29f08, checked in by Aaron Moss <a3moss@…>, 7 years ago

Merge remote-tracking branch 'origin/master' into with_gc

  • Property mode set to 100644
File size: 33.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// 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 "CodeGen/OperatorTable.h" // for isCtorDtor, isCtorDtorAssign
27#include "Common/PassVisitor.h" // for PassVisitor
28#include "Common/ScopedMap.h" // for ScopedMap<>::const_iterator, Scope...
29#include "Common/utility.h" // for cloneAll, operator+
30#include "GenPoly/ScopedSet.h" // for ScopedSet, ScopedSet<>::iterator
31#include "InitTweak/GenInit.h" // for fixReturnStatements
32#include "ResolvExpr/Resolver.h" // for resolveDecl
33#include "SymTab/Mangler.h" // for Mangler
34#include "SynTree/Attribute.h" // For Attribute
35#include "SynTree/Mutator.h" // for maybeMutate
36#include "SynTree/Statement.h" // for CompoundStmt, ReturnStmt, ExprStmt
37#include "SynTree/Type.h" // for FunctionType, Type, TypeInstType
38#include "SynTree/Visitor.h" // for maybeAccept, Visitor, acceptAll
39
40class Attribute;
41
42namespace SymTab {
43 Type * SizeType = 0;
44
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 * );
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 /// inserts a forward declaration for functionDecl into declsToAdd
214 void addForwardDecl( FunctionDecl * functionDecl, std::list< Declaration * > & declsToAdd ) {
215 FunctionDecl * decl = functionDecl->clone();
216 decl->statements = nullptr;
217 declsToAdd.push_back( decl );
218 decl->fixUniqueId();
219 }
220
221 const std::list< TypeDecl * > getGenericParams( Type * t ) {
222 std::list< TypeDecl * > * ret = nullptr;
223 if ( StructInstType * inst = dynamic_cast< StructInstType * > ( t ) ) {
224 ret = inst->get_baseParameters();
225 } else if ( UnionInstType * inst = dynamic_cast< UnionInstType * >( t ) ) {
226 ret = inst->get_baseParameters();
227 }
228 return ret ? *ret : std::list< TypeDecl * >();
229 }
230
231 /// given type T, generate type of default ctor/dtor, i.e. function type void (*) (T *)
232 FunctionType * genDefaultType( Type * paramType ) {
233 const auto & typeParams = getGenericParams( paramType );
234 FunctionType *ftype = new FunctionType( Type::Qualifiers(), false );
235 cloneAll( typeParams, ftype->forall );
236 ObjectDecl *dstParam = new ObjectDecl( "_dst", Type::StorageClasses(), LinkageSpec::Cforall, nullptr, new ReferenceType( Type::Qualifiers(), paramType->clone() ), nullptr );
237 ftype->parameters.push_back( dstParam );
238 return ftype;
239 }
240
241 /// given type T, generate type of copy ctor, i.e. function type void (*) (T *, T)
242 FunctionType * genCopyType( Type * paramType ) {
243 FunctionType *ftype = genDefaultType( paramType );
244 ObjectDecl *srcParam = new ObjectDecl( "_src", Type::StorageClasses(), LinkageSpec::Cforall, nullptr, paramType->clone(), nullptr );
245 ftype->parameters.push_back( srcParam );
246 return ftype;
247 }
248
249 /// given type T, generate type of assignment, i.e. function type T (*) (T *, T)
250 FunctionType * genAssignType( Type * paramType ) {
251 FunctionType *ftype = genCopyType( paramType );
252 ObjectDecl *returnVal = new ObjectDecl( "_ret", Type::StorageClasses(), LinkageSpec::Cforall, nullptr, paramType->clone(), nullptr );
253 ftype->returnVals.push_back( returnVal );
254 return ftype;
255 }
256
257 /// generate a function decl from a name and type. Nesting depth determines whether
258 /// the declaration is static or not; optional paramter determines if declaration is intrinsic
259 FunctionDecl * genFunc( const std::string & fname, FunctionType * ftype, unsigned int functionNesting, bool isIntrinsic = false ) {
260 // Routines at global scope marked "static" to prevent multiple definitions in separate translation units
261 // because each unit generates copies of the default routines for each aggregate.
262 Type::StorageClasses scs = functionNesting > 0 ? Type::StorageClasses() : Type::StorageClasses( Type::Static );
263 LinkageSpec::Spec spec = isIntrinsic ? LinkageSpec::Intrinsic : LinkageSpec::AutoGen;
264 FunctionDecl * decl = new FunctionDecl( fname, scs, spec, ftype, new CompoundStmt(),
265 std::list< Attribute * >(), Type::FuncSpecifiers( Type::Inline ) );
266 decl->fixUniqueId();
267 return decl;
268 }
269
270 Type * declToType( Declaration * decl ) {
271 if ( DeclarationWithType * dwt = dynamic_cast< DeclarationWithType * >( decl ) ) {
272 return dwt->get_type();
273 }
274 return nullptr;
275 }
276
277 Type * declToTypeDeclBase( Declaration * decl ) {
278 if ( TypeDecl * td = dynamic_cast< TypeDecl * >( decl ) ) {
279 return td->base;
280 }
281 return nullptr;
282 }
283
284 //=============================================================================================
285 // FuncGenerator member definitions
286 //=============================================================================================
287 void FuncGenerator::genStandardFuncs() {
288 std::list< FunctionDecl * > newFuncs;
289 generatePrototypes( newFuncs );
290
291 for ( FunctionDecl * dcl : newFuncs ) {
292 genFuncBody( dcl );
293 if ( CodeGen::isAssignment( dcl->name ) ) {
294 // assignment needs to return a value
295 FunctionType * assignType = dcl->type;
296 assert( assignType->parameters.size() == 2 );
297 assert( assignType->returnVals.size() == 1 );
298 ObjectDecl * dstParam = strict_dynamic_cast< ObjectDecl * >( assignType->parameters.front() );
299 dcl->statements->push_back( new ReturnStmt( new VariableExpr( dstParam ) ) );
300 }
301 resolve( dcl );
302 }
303 }
304
305 void FuncGenerator::generatePrototypes( std::list< FunctionDecl * > & newFuncs ) {
306 bool concurrent_type = isConcurrentType();
307 for ( const FuncData & d : data ) {
308 // generate a function (?{}, ?=?, ^?{}) based on the current FuncData.
309 FunctionType * ftype = d.genType( type );
310
311 // destructor for concurrent type must be mutex
312 if ( concurrent_type && CodeGen::isDestructor( d.fname ) ) {
313 ftype->parameters.front()->get_type()->set_mutex( true );
314 }
315
316 newFuncs.push_back( genFunc( d.fname, ftype, functionNesting ) );
317 }
318 }
319
320 void FuncGenerator::resolve( FunctionDecl * dcl ) {
321 try {
322 ResolvExpr::resolveDecl( dcl, indexer );
323 if ( functionNesting == 0 ) {
324 // forward declare if top-level struct, so that
325 // type is complete as soon as its body ends
326 // Note: this is necessary if we want structs which contain
327 // generic (otype) structs as members.
328 addForwardDecl( dcl, forwards );
329 }
330 definitions.push_back( dcl );
331 indexer.addId( dcl );
332 } catch ( SemanticErrorException & ) {
333 // okay if decl does not resolve - that means the function should not be generated
334 }
335 }
336
337 bool StructFuncGenerator::shouldAutogen() const {
338 // Builtins do not use autogeneration.
339 return ! aggregateDecl->linkage.is_builtin;
340 }
341 bool StructFuncGenerator::isConcurrentType() const { return aggregateDecl->is_thread() || aggregateDecl->is_monitor(); }
342
343 void StructFuncGenerator::genFuncBody( FunctionDecl * dcl ) {
344 // generate appropriate calls to member ctor, assignment
345 // destructor needs to do everything in reverse, so pass "forward" based on whether the function is a destructor
346 if ( ! CodeGen::isDestructor( dcl->name ) ) {
347 makeFunctionBody( aggregateDecl->members.begin(), aggregateDecl->members.end(), dcl );
348 } else {
349 makeFunctionBody( aggregateDecl->members.rbegin(), aggregateDecl->members.rend(), dcl, false );
350 }
351 }
352
353 void StructFuncGenerator::genFieldCtors() {
354 // field ctors are only generated if default constructor and copy constructor are both generated
355 unsigned numCtors = std::count_if( definitions.begin(), definitions.end(), [](Declaration * dcl) { return CodeGen::isConstructor( dcl->name ); } );
356
357 // Field constructors are only generated if default and copy constructor
358 // are generated, since they need access to both
359 if ( numCtors != 2 ) return;
360
361 // create constructors which take each member type as a parameter.
362 // for example, for struct A { int x, y; }; generate
363 // void ?{}(A *, int) and void ?{}(A *, int, int)
364 FunctionType * memCtorType = genDefaultType( type );
365 for ( Declaration * member : aggregateDecl->members ) {
366 DeclarationWithType * field = strict_dynamic_cast<DeclarationWithType *>( member );
367 if ( isUnnamedBitfield( dynamic_cast< ObjectDecl * > ( field ) ) ) {
368 // don't make a function whose parameter is an unnamed bitfield
369 continue;
370 }
371 // do not carry over field's attributes to parameter type
372 Type * paramType = field->get_type()->clone();
373 paramType->attributes.clear();
374 // add a parameter corresponding to this field
375 ObjectDecl * param = new ObjectDecl( field->name, Type::StorageClasses(), LinkageSpec::Cforall, nullptr, paramType, nullptr );
376 cloneAll_if( field->attributes, param->attributes, [](Attribute * attr) { return attr->isValidOnFuncParam(); } );
377 memCtorType->parameters.push_back( param );
378 FunctionDecl * ctor = genFunc( "?{}", memCtorType->clone(), functionNesting );
379 makeFieldCtorBody( aggregateDecl->members.begin(), aggregateDecl->members.end(), ctor );
380 resolve( ctor );
381 }
382 }
383
384 void StructFuncGenerator::makeMemberOp( ObjectDecl * dstParam, Expression * src, DeclarationWithType * field, FunctionDecl * func, bool forward ) {
385 InitTweak::InitExpander srcParam( src );
386
387 // assign to destination
388 Expression *dstselect = new MemberExpr( field, new CastExpr( new VariableExpr( dstParam ), strict_dynamic_cast< ReferenceType* >( dstParam->get_type() )->base->clone() ) );
389 genImplicitCall( srcParam, dstselect, func->name, back_inserter( func->statements->kids ), field, forward );
390 }
391
392 template<typename Iterator>
393 void StructFuncGenerator::makeFunctionBody( Iterator member, Iterator end, FunctionDecl * func, bool forward ) {
394 for ( ; member != end; ++member ) {
395 if ( DeclarationWithType *field = dynamic_cast< DeclarationWithType * >( *member ) ) { // otherwise some form of type declaration, e.g. Aggregate
396 // query the type qualifiers of this field and skip assigning it if it is marked const.
397 // If it is an array type, we need to strip off the array layers to find its qualifiers.
398 Type * type = field->get_type();
399 while ( ArrayType * at = dynamic_cast< ArrayType * >( type ) ) {
400 type = at->get_base();
401 }
402
403 if ( type->get_const() && CodeGen::isAssignment( func->name ) ) {
404 // don't assign const members, but do construct/destruct
405 continue;
406 }
407
408 assert( ! func->get_functionType()->get_parameters().empty() );
409 ObjectDecl * dstParam = dynamic_cast<ObjectDecl*>( func->get_functionType()->get_parameters().front() );
410 ObjectDecl * srcParam = nullptr;
411 if ( func->get_functionType()->get_parameters().size() == 2 ) {
412 srcParam = dynamic_cast<ObjectDecl*>( func->get_functionType()->get_parameters().back() );
413 }
414
415 // srcParam may be NULL, in which case we have default ctor/dtor
416 assert( dstParam );
417
418 Expression *srcselect = srcParam ? new MemberExpr( field, new VariableExpr( srcParam ) ) : nullptr;
419 makeMemberOp( dstParam, srcselect, field, func, forward );
420 } // if
421 } // for
422 } // makeFunctionBody
423
424 template<typename Iterator>
425 void StructFuncGenerator::makeFieldCtorBody( Iterator member, Iterator end, FunctionDecl * func ) {
426 FunctionType * ftype = func->type;
427 std::list<DeclarationWithType*> & params = ftype->parameters;
428 assert( params.size() >= 2 ); // should not call this function for default ctor, etc.
429
430 // skip 'this' parameter
431 ObjectDecl * dstParam = dynamic_cast<ObjectDecl*>( params.front() );
432 assert( dstParam );
433 std::list<DeclarationWithType*>::iterator parameter = params.begin()+1;
434 for ( ; member != end; ++member ) {
435 if ( DeclarationWithType * field = dynamic_cast<DeclarationWithType*>( *member ) ) {
436 if ( isUnnamedBitfield( dynamic_cast< ObjectDecl * > ( field ) ) ) {
437 // don't make a function whose parameter is an unnamed bitfield
438 continue;
439 } else if ( parameter != params.end() ) {
440 // matching parameter, initialize field with copy ctor
441 Expression *srcselect = new VariableExpr(*parameter);
442 makeMemberOp( dstParam, srcselect, field, func );
443 ++parameter;
444 } else {
445 // no matching parameter, initialize field with default ctor
446 makeMemberOp( dstParam, nullptr, field, func );
447 }
448 }
449 }
450 }
451
452 bool UnionFuncGenerator::shouldAutogen() const {
453 // Builtins do not use autogeneration.
454 return ! aggregateDecl->linkage.is_builtin;
455 }
456
457 // xxx - is this right?
458 bool UnionFuncGenerator::isConcurrentType() const { return false; };
459
460 /// generate a single union assignment expression (using memcpy)
461 template< typename OutputIterator >
462 void UnionFuncGenerator::makeMemberOp( ObjectDecl * srcParam, ObjectDecl * dstParam, OutputIterator out ) {
463 UntypedExpr *copy = new UntypedExpr( new NameExpr( "__builtin_memcpy" ) );
464 copy->args.push_back( new AddressExpr( new VariableExpr( dstParam ) ) );
465 copy->args.push_back( new AddressExpr( new VariableExpr( srcParam ) ) );
466 copy->args.push_back( new SizeofExpr( srcParam->get_type()->clone() ) );
467 *out++ = new ExprStmt( copy );
468 }
469
470 /// generates the body of a union assignment/copy constructor/field constructor
471 void UnionFuncGenerator::genFuncBody( FunctionDecl * funcDecl ) {
472 FunctionType * ftype = funcDecl->type;
473 if ( InitTweak::isCopyConstructor( funcDecl ) || InitTweak::isAssignment( funcDecl ) ) {
474 assert( ftype->parameters.size() == 2 );
475 ObjectDecl * dstParam = strict_dynamic_cast< ObjectDecl * >( ftype->parameters.front() );
476 ObjectDecl * srcParam = strict_dynamic_cast< ObjectDecl * >( ftype->parameters.back() );
477 makeMemberOp( srcParam, dstParam, back_inserter( funcDecl->statements->kids ) );
478 } else {
479 // default ctor/dtor body is empty - add unused attribute to parameter to silence warnings
480 assert( ftype->parameters.size() == 1 );
481 ObjectDecl * dstParam = strict_dynamic_cast< ObjectDecl * >( ftype->parameters.front() );
482 dstParam->attributes.push_back( new Attribute( "unused" ) );
483 }
484 }
485
486 /// generate the body of a constructor which takes parameters that match fields, e.g.
487 /// void ?{}(A *, int) and void?{}(A *, int, int) for a struct A which has two int fields.
488 void UnionFuncGenerator::genFieldCtors() {
489 // field ctors are only generated if default constructor and copy constructor are both generated
490 unsigned numCtors = std::count_if( definitions.begin(), definitions.end(), [](Declaration * dcl) { return CodeGen::isConstructor( dcl->get_name() ); } );
491
492 // Field constructors are only generated if default and copy constructor
493 // are generated, since they need access to both
494 if ( numCtors != 2 ) return;
495
496 // create a constructor which takes the first member type as a parameter.
497 // for example, for Union A { int x; double y; }; generate
498 // void ?{}(A *, int)
499 // This is to mimic C's behaviour which initializes the first member of the union.
500 FunctionType * memCtorType = genDefaultType( type );
501 for ( Declaration * member : aggregateDecl->members ) {
502 DeclarationWithType * field = strict_dynamic_cast<DeclarationWithType *>( member );
503 if ( isUnnamedBitfield( dynamic_cast< ObjectDecl * > ( field ) ) ) {
504 // don't make a function whose parameter is an unnamed bitfield
505 break;
506 }
507 // do not carry over field's attributes to parameter type
508 Type * paramType = field->get_type()->clone();
509 paramType->attributes.clear();
510 // add a parameter corresponding to this field
511 memCtorType->parameters.push_back( new ObjectDecl( field->name, Type::StorageClasses(), LinkageSpec::Cforall, nullptr, paramType, nullptr ) );
512 FunctionDecl * ctor = genFunc( "?{}", memCtorType->clone(), functionNesting );
513 ObjectDecl * srcParam = strict_dynamic_cast<ObjectDecl *>( ctor->type->parameters.back() );
514 srcParam->fixUniqueId();
515 ObjectDecl * dstParam = InitTweak::getParamThis( ctor->type );
516 makeMemberOp( srcParam, dstParam, back_inserter( ctor->statements->kids ) );
517 resolve( ctor );
518 // only generate one field ctor for unions
519 break;
520 }
521 }
522
523 void EnumFuncGenerator::genFuncBody( FunctionDecl * funcDecl ) {
524 // xxx - Temporary: make these functions intrinsic so they codegen as C assignment.
525 // Really they're something of a cross between instrinsic and autogen, so should
526 // probably make a new linkage type
527 funcDecl->linkage = LinkageSpec::Intrinsic;
528 FunctionType * ftype = funcDecl->type;
529 if ( InitTweak::isCopyConstructor( funcDecl ) || InitTweak::isAssignment( funcDecl ) ) {
530 assert( ftype->parameters.size() == 2 );
531 ObjectDecl * dstParam = strict_dynamic_cast< ObjectDecl * >( ftype->parameters.front() );
532 ObjectDecl * srcParam = strict_dynamic_cast< ObjectDecl * >( ftype->parameters.back() );
533
534 // enum copy construct and assignment is just C-style assignment.
535 // this looks like a bad recursive call, but code gen will turn it into
536 // a C-style assignment.
537 // This happens before function pointer type conversion, so need to do it manually here
538 ApplicationExpr * callExpr = new ApplicationExpr( VariableExpr::functionPointer( funcDecl ) );
539 callExpr->get_args().push_back( new VariableExpr( dstParam ) );
540 callExpr->get_args().push_back( new VariableExpr( srcParam ) );
541 funcDecl->statements->push_back( new ExprStmt( callExpr ) );
542 } else {
543 // default ctor/dtor body is empty - add unused attribute to parameter to silence warnings
544 assert( ftype->parameters.size() == 1 );
545 ObjectDecl * dstParam = strict_dynamic_cast< ObjectDecl * >( ftype->parameters.front() );
546 dstParam->attributes.push_back( new Attribute( "unused" ) );
547 }
548 }
549
550 bool EnumFuncGenerator::shouldAutogen() const { return true; }
551 bool EnumFuncGenerator::isConcurrentType() const { return false; }
552 // enums do not have field constructors
553 void EnumFuncGenerator::genFieldCtors() {}
554
555 bool TypeFuncGenerator::shouldAutogen() const { return true; };
556
557 void TypeFuncGenerator::genFuncBody( FunctionDecl * dcl ) {
558 FunctionType * ftype = dcl->type;
559 assertf( ftype->parameters.size() == 1 || ftype->parameters.size() == 2, "Incorrect number of parameters in autogenerated typedecl function: %zd", ftype->parameters.size() );
560 DeclarationWithType * dst = ftype->parameters.front();
561 DeclarationWithType * src = ftype->parameters.size() == 2 ? ftype->parameters.back() : nullptr;
562 // generate appropriate calls to member ctor, assignment
563 UntypedExpr * expr = new UntypedExpr( new NameExpr( dcl->name ) );
564 expr->args.push_back( new CastExpr( new VariableExpr( dst ), new ReferenceType( Type::Qualifiers(), typeDecl->base->clone() ) ) );
565 if ( src ) expr->args.push_back( new CastExpr( new VariableExpr( src ), typeDecl->base->clone() ) );
566 dcl->statements->kids.push_back( new ExprStmt( expr ) );
567 };
568
569 // xxx - should reach in and determine if base type is concurrent?
570 bool TypeFuncGenerator::isConcurrentType() const { return false; };
571
572 // opaque types do not have field constructors
573 void TypeFuncGenerator::genFieldCtors() {};
574
575 //=============================================================================================
576 // Visitor definitions
577 //=============================================================================================
578 AutogenerateRoutines::AutogenerateRoutines() {
579 // the order here determines the order that these functions are generated.
580 // assignment should come last since it uses copy constructor in return.
581 data.emplace_back( "?{}", genDefaultType );
582 data.emplace_back( "?{}", genCopyType );
583 data.emplace_back( "^?{}", genDefaultType );
584 data.emplace_back( "?=?", genAssignType );
585 }
586
587 void AutogenerateRoutines::previsit( EnumDecl * enumDecl ) {
588 // must visit children (enum constants) to add them to the indexer
589 if ( enumDecl->has_body() ) {
590 auto enumInst = new EnumInstType{ Type::Qualifiers(), enumDecl->get_name() };
591 enumInst->set_baseEnum( enumDecl );
592 EnumFuncGenerator gen( enumInst, data, functionNesting, indexer );
593 generateFunctions( gen, declsToAddAfter );
594 }
595 }
596
597 void AutogenerateRoutines::previsit( StructDecl * structDecl ) {
598 visit_children = false;
599 if ( structDecl->has_body() ) {
600 auto structInst = new StructInstType{ Type::Qualifiers(), structDecl->name };
601 structInst->set_baseStruct( structDecl );
602 for ( TypeDecl * typeDecl : structDecl->parameters ) {
603 structInst->parameters.push_back( new TypeExpr( new TypeInstType( Type::Qualifiers(), typeDecl->name, typeDecl ) ) );
604 }
605 StructFuncGenerator gen( structDecl, structInst, data, functionNesting, indexer );
606 generateFunctions( gen, declsToAddAfter );
607 } // if
608 }
609
610 void AutogenerateRoutines::previsit( UnionDecl * unionDecl ) {
611 visit_children = false;
612 if ( unionDecl->has_body() ) {
613 auto unionInst = new UnionInstType{ Type::Qualifiers(), unionDecl->get_name() };
614 unionInst->set_baseUnion( unionDecl );
615 for ( TypeDecl * typeDecl : unionDecl->get_parameters() ) {
616 unionInst->get_parameters().push_back( new TypeExpr( new TypeInstType( Type::Qualifiers(), typeDecl->get_name(), typeDecl ) ) );
617 }
618 UnionFuncGenerator gen( unionDecl, unionInst, data, functionNesting, indexer );
619 generateFunctions( gen, declsToAddAfter );
620 } // if
621 }
622
623 // generate ctor/dtors/assign for typedecls, e.g., otype T = int *;
624 void AutogenerateRoutines::previsit( TypeDecl * typeDecl ) {
625 if ( ! typeDecl->base ) return;
626
627 auto refType = new TypeInstType{ Type::Qualifiers(), typeDecl->name, typeDecl };
628 TypeFuncGenerator gen( typeDecl, refType, data, functionNesting, indexer );
629 generateFunctions( gen, declsToAddAfter );
630
631 }
632
633 void AutogenerateRoutines::previsit( TraitDecl * ) {
634 // ensure that we don't add assignment ops for types defined as part of the trait
635 visit_children = false;
636 }
637
638 void AutogenerateRoutines::previsit( FunctionDecl * ) {
639 // Track whether we're currently in a function.
640 // Can ignore function type idiosyncrasies, because function type can never
641 // declare a new type.
642 functionNesting += 1;
643 GuardAction( [this]() { functionNesting -= 1; } );
644 }
645
646 void AutogenerateRoutines::previsit( CompoundStmt * ) {
647 GuardScope( structsDone );
648 }
649
650 void makeTupleFunctionBody( FunctionDecl * function ) {
651 FunctionType * ftype = function->get_functionType();
652 assertf( ftype->get_parameters().size() == 1 || ftype->get_parameters().size() == 2, "too many parameters in generated tuple function" );
653
654 UntypedExpr * untyped = new UntypedExpr( new NameExpr( function->get_name() ) );
655
656 /// xxx - &* is used to make this easier for later passes to handle
657 untyped->get_args().push_back( new AddressExpr( UntypedExpr::createDeref( new VariableExpr( ftype->get_parameters().front() ) ) ) );
658 if ( ftype->get_parameters().size() == 2 ) {
659 untyped->get_args().push_back( new VariableExpr( ftype->get_parameters().back() ) );
660 }
661 function->get_statements()->get_kids().push_back( new ExprStmt( untyped ) );
662 function->get_statements()->get_kids().push_back( new ReturnStmt( UntypedExpr::createDeref( new VariableExpr( ftype->get_parameters().front() ) ) ) );
663 }
664
665 void AutogenTupleRoutines::postvisit( TupleType * tupleType ) {
666 std::string mangleName = SymTab::Mangler::mangleType( tupleType );
667 if ( seenTuples.find( mangleName ) != seenTuples.end() ) return;
668 seenTuples.insert( mangleName );
669
670 // T ?=?(T *, T);
671 FunctionType *assignType = genAssignType( tupleType );
672
673 // void ?{}(T *); void ^?{}(T *);
674 FunctionType *ctorType = genDefaultType( tupleType );
675 FunctionType *dtorType = genDefaultType( tupleType );
676
677 // void ?{}(T *, T);
678 FunctionType *copyCtorType = genCopyType( tupleType );
679
680 std::set< TypeDecl* > done;
681 std::list< TypeDecl * > typeParams;
682 for ( Type * t : *tupleType ) {
683 if ( TypeInstType * ty = dynamic_cast< TypeInstType * >( t ) ) {
684 if ( ! done.count( ty->get_baseType() ) ) {
685 TypeDecl * newDecl = new TypeDecl( ty->get_baseType()->get_name(), Type::StorageClasses(), nullptr, TypeDecl::Dtype, true );
686 TypeInstType * inst = new TypeInstType( Type::Qualifiers(), newDecl->get_name(), newDecl );
687 newDecl->get_assertions().push_back( new FunctionDecl( "?=?", Type::StorageClasses(), LinkageSpec::Cforall, genAssignType( inst ), nullptr,
688 std::list< Attribute * >(), Type::FuncSpecifiers( Type::Inline ) ) );
689 newDecl->get_assertions().push_back( new FunctionDecl( "?{}", Type::StorageClasses(), LinkageSpec::Cforall, genDefaultType( inst ), nullptr,
690 std::list< Attribute * >(), Type::FuncSpecifiers( Type::Inline ) ) );
691 newDecl->get_assertions().push_back( new FunctionDecl( "?{}", Type::StorageClasses(), LinkageSpec::Cforall, genCopyType( inst ), nullptr,
692 std::list< Attribute * >(), Type::FuncSpecifiers( Type::Inline ) ) );
693 newDecl->get_assertions().push_back( new FunctionDecl( "^?{}", Type::StorageClasses(), LinkageSpec::Cforall, genDefaultType( inst ), nullptr,
694 std::list< Attribute * >(), Type::FuncSpecifiers( Type::Inline ) ) );
695 typeParams.push_back( newDecl );
696 done.insert( ty->get_baseType() );
697 }
698 }
699 }
700 cloneAll( typeParams, ctorType->get_forall() );
701 cloneAll( typeParams, dtorType->get_forall() );
702 cloneAll( typeParams, copyCtorType->get_forall() );
703 cloneAll( typeParams, assignType->get_forall() );
704
705 FunctionDecl *assignDecl = genFunc( "?=?", assignType, functionNesting );
706 FunctionDecl *ctorDecl = genFunc( "?{}", ctorType, functionNesting );
707 FunctionDecl *copyCtorDecl = genFunc( "?{}", copyCtorType, functionNesting );
708 FunctionDecl *dtorDecl = genFunc( "^?{}", dtorType, functionNesting );
709
710 makeTupleFunctionBody( assignDecl );
711 makeTupleFunctionBody( ctorDecl );
712 makeTupleFunctionBody( copyCtorDecl );
713 makeTupleFunctionBody( dtorDecl );
714
715 declsToAddBefore.push_back( ctorDecl );
716 declsToAddBefore.push_back( copyCtorDecl );
717 declsToAddBefore.push_back( dtorDecl );
718 declsToAddBefore.push_back( assignDecl ); // assignment should come last since it uses copy constructor in return
719 }
720
721 void AutogenTupleRoutines::previsit( FunctionDecl *functionDecl ) {
722 visit_children = false;
723 maybeAccept( functionDecl->type, *visitor );
724 functionNesting += 1;
725 maybeAccept( functionDecl->statements, *visitor );
726 functionNesting -= 1;
727 }
728
729 void AutogenTupleRoutines::previsit( CompoundStmt * ) {
730 GuardScope( seenTuples );
731 }
732} // SymTab
733
734// Local Variables: //
735// tab-width: 4 //
736// mode: c++ //
737// compile-command: "make install" //
738// End: //
Note: See TracBrowser for help on using the repository browser.