source: src/SymTab/Autogen.cc@ 21ea170

ADT aaron-thesis arm-eh ast-experimental cleanup-dtors deferred_resn demangler enum forall-pointer-decay jacob/cs343-translation jenkins-sandbox new-ast new-ast-unique-expr new-env no_list persistent-indexer pthread-emulation qualifiedEnum resolv-new with_gc
Last change on this file since 21ea170 was 189d800, checked in by Rob Schluntz <rschlunt@…>, 8 years ago

Rework autogen to resolve struct functions as they are generated [fixes #43]

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