source: src/SymTab/Autogen.cc@ ca278c1

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 ca278c1 was 8404321, checked in by Rob Schluntz <rschlunt@…>, 8 years ago

Add genCopyType and genDefaultType to Autogen.h

  • Property mode set to 100644
File size: 36.6 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 {
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 const std::list< TypeDecl* > & typeParams;
197 OutputIterator out;
198 FuncGenerator( const Container & container, Type *refType, unsigned int functionNesting, const std::list< TypeDecl* > & typeParams, OutputIterator out ) : container( container ), refType( refType ), functionNesting( functionNesting ), typeParams( typeParams ), out( out ) {}
199
200 /// generates a function (?{}, ?=?, ^?{}) based on the data argument and members. If function is generated, inserts the type into the map.
201 void gen( const FuncData & data, bool concurrent_type ) {
202 if ( ! shouldGenerate( data.map, container ) ) return;
203 FunctionType * ftype = data.genType( refType );
204
205 if ( concurrent_type && CodeGen::isDestructor( data.fname ) ) {
206 ftype->parameters.front()->get_type()->set_mutex( true );
207 }
208
209 cloneAll( typeParams, ftype->forall );
210 *out++ = genFunc( data.fname, ftype, functionNesting );
211 data.map.insert( Mangler::mangleType( refType ), true );
212 }
213 };
214
215 template< typename OutputIterator, typename Container >
216 FuncGenerator<OutputIterator, Container> makeFuncGenerator( const Container & container, Type *refType, unsigned int functionNesting, const std::list< TypeDecl* > & typeParams, OutputIterator out ) {
217 return FuncGenerator<OutputIterator, Container>( container, refType, functionNesting, typeParams, out );
218 }
219
220 /// generates a single enumeration assignment expression
221 ApplicationExpr * genEnumAssign( FunctionType * ftype, FunctionDecl * assignDecl ) {
222 // enum copy construct and assignment is just C-style assignment.
223 // this looks like a bad recursive call, but code gen will turn it into
224 // a C-style assignment.
225 // This happens before function pointer type conversion, so need to do it manually here
226 // NOTE: ftype is not necessarily the functionType belonging to assignDecl - ftype is the
227 // type of the function that this expression is being generated for (so that the correct
228 // parameters) are using in the variable exprs
229 assert( ftype->get_parameters().size() == 2 );
230 ObjectDecl * dstParam = strict_dynamic_cast< ObjectDecl * >( ftype->get_parameters().front() );
231 ObjectDecl * srcParam = strict_dynamic_cast< ObjectDecl * >( ftype->get_parameters().back() );
232
233 VariableExpr * assignVarExpr = new VariableExpr( assignDecl );
234 Type * assignVarExprType = assignVarExpr->get_result();
235 assignVarExprType = new PointerType( Type::Qualifiers(), assignVarExprType );
236 assignVarExpr->set_result( assignVarExprType );
237 ApplicationExpr * assignExpr = new ApplicationExpr( assignVarExpr );
238 assignExpr->get_args().push_back( new VariableExpr( dstParam ) );
239 assignExpr->get_args().push_back( new VariableExpr( srcParam ) );
240 return assignExpr;
241 }
242
243 // E ?=?(E volatile*, int),
244 // ?=?(E _Atomic volatile*, int);
245 void makeEnumFunctions( EnumInstType *refType, unsigned int functionNesting, std::list< Declaration * > &declsToAdd ) {
246
247 // T ?=?(E *, E);
248 FunctionType *assignType = genAssignType( refType );
249
250 // void ?{}(E *); void ^?{}(E *);
251 FunctionType * ctorType = genDefaultType( refType->clone() );
252 FunctionType * dtorType = genDefaultType( refType->clone() );
253
254 // void ?{}(E *, E);
255 FunctionType *copyCtorType = genCopyType( refType->clone() );
256
257 // add unused attribute to parameters of default constructor and destructor
258 ctorType->get_parameters().front()->get_attributes().push_back( new Attribute( "unused" ) );
259 dtorType->get_parameters().front()->get_attributes().push_back( new Attribute( "unused" ) );
260
261 // xxx - should we also generate void ?{}(E *, int) and E ?{}(E *, E)?
262 // right now these cases work, but that might change.
263
264 // xxx - Temporary: make these functions intrinsic so they codegen as C assignment.
265 // Really they're something of a cross between instrinsic and autogen, so should
266 // probably make a new linkage type
267 FunctionDecl *assignDecl = genFunc( "?=?", assignType, functionNesting, true );
268 FunctionDecl *ctorDecl = genFunc( "?{}", ctorType, functionNesting, true );
269 FunctionDecl *copyCtorDecl = genFunc( "?{}", copyCtorType, functionNesting, true );
270 FunctionDecl *dtorDecl = genFunc( "^?{}", dtorType, functionNesting, true );
271
272 // body is either return stmt or expr stmt
273 assignDecl->get_statements()->get_kids().push_back( new ReturnStmt( noLabels, genEnumAssign( assignType, assignDecl ) ) );
274 copyCtorDecl->get_statements()->get_kids().push_back( new ExprStmt( noLabels, genEnumAssign( copyCtorType, assignDecl ) ) );
275
276 declsToAdd.push_back( ctorDecl );
277 declsToAdd.push_back( copyCtorDecl );
278 declsToAdd.push_back( dtorDecl );
279 declsToAdd.push_back( assignDecl ); // assignment should come last since it uses copy constructor in return
280 }
281
282 /// generates a single struct member operation (constructor call, destructor call, assignment call)
283 void makeStructMemberOp( ObjectDecl * dstParam, Expression * src, DeclarationWithType * field, FunctionDecl * func, bool forward = true ) {
284 InitTweak::InitExpander srcParam( src );
285
286 // assign to destination
287 Expression *dstselect = new MemberExpr( field, new CastExpr( new VariableExpr( dstParam ), strict_dynamic_cast< ReferenceType* >( dstParam->get_type() )->get_base()->clone() ) );
288 genImplicitCall( srcParam, dstselect, func->get_name(), back_inserter( func->get_statements()->get_kids() ), field, forward );
289 }
290
291 /// 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
292 template<typename Iterator>
293 void makeStructFunctionBody( Iterator member, Iterator end, FunctionDecl * func, bool forward = true ) {
294 for ( ; member != end; ++member ) {
295 if ( DeclarationWithType *field = dynamic_cast< DeclarationWithType * >( *member ) ) { // otherwise some form of type declaration, e.g. Aggregate
296 // query the type qualifiers of this field and skip assigning it if it is marked const.
297 // If it is an array type, we need to strip off the array layers to find its qualifiers.
298 Type * type = field->get_type();
299 while ( ArrayType * at = dynamic_cast< ArrayType * >( type ) ) {
300 type = at->get_base();
301 }
302
303 if ( type->get_const() && func->get_name() == "?=?" ) {
304 // don't assign const members, but do construct/destruct
305 continue;
306 }
307
308 if ( field->get_name() == "" ) {
309 // don't assign to anonymous members
310 // xxx - this is a temporary fix. Anonymous members tie into
311 // our inheritance model. I think the correct way to handle this is to
312 // cast the structure to the type of the member and let the resolver
313 // figure out whether it's valid and have a pass afterwards that fixes
314 // the assignment to use pointer arithmetic with the offset of the
315 // member, much like how generic type members are handled.
316 continue;
317 }
318
319 assert( ! func->get_functionType()->get_parameters().empty() );
320 ObjectDecl * dstParam = dynamic_cast<ObjectDecl*>( func->get_functionType()->get_parameters().front() );
321 ObjectDecl * srcParam = nullptr;
322 if ( func->get_functionType()->get_parameters().size() == 2 ) {
323 srcParam = dynamic_cast<ObjectDecl*>( func->get_functionType()->get_parameters().back() );
324 }
325 // srcParam may be NULL, in which case we have default ctor/dtor
326 assert( dstParam );
327
328 Expression *srcselect = srcParam ? new MemberExpr( field, new VariableExpr( srcParam ) ) : nullptr;
329 makeStructMemberOp( dstParam, srcselect, field, func, forward );
330 } // if
331 } // for
332 } // makeStructFunctionBody
333
334 /// generate the body of a constructor which takes parameters that match fields, e.g.
335 /// void ?{}(A *, int) and void?{}(A *, int, int) for a struct A which has two int fields.
336 template<typename Iterator>
337 void makeStructFieldCtorBody( Iterator member, Iterator end, FunctionDecl * func ) {
338 FunctionType * ftype = func->get_functionType();
339 std::list<DeclarationWithType*> & params = ftype->get_parameters();
340 assert( params.size() >= 2 ); // should not call this function for default ctor, etc.
341
342 // skip 'this' parameter
343 ObjectDecl * dstParam = dynamic_cast<ObjectDecl*>( params.front() );
344 assert( dstParam );
345 std::list<DeclarationWithType*>::iterator parameter = params.begin()+1;
346 for ( ; member != end; ++member ) {
347 if ( DeclarationWithType * field = dynamic_cast<DeclarationWithType*>( *member ) ) {
348 if ( isUnnamedBitfield( dynamic_cast< ObjectDecl * > ( field ) ) ) {
349 // don't make a function whose parameter is an unnamed bitfield
350 continue;
351 } else if ( field->get_name() == "" ) {
352 // don't assign to anonymous members
353 // xxx - this is a temporary fix. Anonymous members tie into
354 // our inheritance model. I think the correct way to handle this is to
355 // cast the structure to the type of the member and let the resolver
356 // figure out whether it's valid and have a pass afterwards that fixes
357 // the assignment to use pointer arithmetic with the offset of the
358 // member, much like how generic type members are handled.
359 continue;
360 } else if ( parameter != params.end() ) {
361 // matching parameter, initialize field with copy ctor
362 Expression *srcselect = new VariableExpr(*parameter);
363 makeStructMemberOp( dstParam, srcselect, field, func );
364 ++parameter;
365 } else {
366 // no matching parameter, initialize field with default ctor
367 makeStructMemberOp( dstParam, nullptr, field, func );
368 }
369 }
370 }
371 }
372
373 Type * declToType( Declaration * decl ) {
374 if ( DeclarationWithType * dwt = dynamic_cast< DeclarationWithType * >( decl ) ) {
375 return dwt->get_type();
376 }
377 return nullptr;
378 }
379
380 /// generates struct constructors, destructor, and assignment functions
381 void makeStructFunctions( StructDecl *aggregateDecl, StructInstType *refType, unsigned int functionNesting, std::list< Declaration * > & declsToAdd, const std::vector< FuncData > & data ) {
382 // Builtins do not use autogeneration.
383 if ( LinkageSpec::isBuiltin( aggregateDecl->get_linkage() ) ) {
384 return;
385 }
386
387 // Make function polymorphic in same parameters as generic struct, if applicable
388 const std::list< TypeDecl * > & typeParams = aggregateDecl->get_parameters(); // List of type variables to be placed on the generated functions
389
390 // generate each of the functions based on the supplied FuncData objects
391 std::list< FunctionDecl * > newFuncs;
392 // structure that iterates aggregate decl members, returning their types
393 auto generator = makeFuncGenerator( lazy_map( aggregateDecl->members, declToType ), refType, functionNesting, typeParams, back_inserter( newFuncs ) );
394 for ( const FuncData & d : data ) {
395 generator.gen( d, aggregateDecl->is_thread() || aggregateDecl->is_monitor() );
396 }
397
398 // field ctors are only generated if default constructor and copy constructor are both generated
399 unsigned numCtors = std::count_if( newFuncs.begin(), newFuncs.end(), [](FunctionDecl * dcl) { return CodeGen::isConstructor( dcl->get_name() ); } );
400
401 if ( functionNesting == 0 ) {
402 // forward declare if top-level struct, so that
403 // type is complete as soon as its body ends
404 // Note: this is necessary if we want structs which contain
405 // generic (otype) structs as members.
406 for ( FunctionDecl * dcl : newFuncs ) {
407 addForwardDecl( dcl, declsToAdd );
408 }
409 }
410
411 for ( FunctionDecl * dcl : newFuncs ) {
412 // generate appropriate calls to member ctor, assignment
413 // destructor needs to do everything in reverse, so pass "forward" based on whether the function is a destructor
414 if ( ! CodeGen::isDestructor( dcl->get_name() ) ) {
415 makeStructFunctionBody( aggregateDecl->get_members().begin(), aggregateDecl->get_members().end(), dcl );
416 } else {
417 makeStructFunctionBody( aggregateDecl->get_members().rbegin(), aggregateDecl->get_members().rend(), dcl, false );
418 }
419 if ( CodeGen::isAssignment( dcl->get_name() ) ) {
420 // assignment needs to return a value
421 FunctionType * assignType = dcl->get_functionType();
422 assert( assignType->get_parameters().size() == 2 );
423 ObjectDecl * srcParam = strict_dynamic_cast< ObjectDecl * >( assignType->get_parameters().back() );
424 dcl->get_statements()->get_kids().push_back( new ReturnStmt( noLabels, new VariableExpr( srcParam ) ) );
425 }
426 declsToAdd.push_back( dcl );
427 }
428
429 // create constructors which take each member type as a parameter.
430 // for example, for struct A { int x, y; }; generate
431 // void ?{}(A *, int) and void ?{}(A *, int, int)
432 // Field constructors are only generated if default and copy constructor
433 // are generated, since they need access to both
434 if ( numCtors == 2 ) {
435 FunctionType * memCtorType = genDefaultType( refType );
436 cloneAll( typeParams, memCtorType->get_forall() );
437 for ( std::list<Declaration *>::iterator i = aggregateDecl->get_members().begin(); i != aggregateDecl->get_members().end(); ++i ) {
438 DeclarationWithType * member = dynamic_cast<DeclarationWithType *>( *i );
439 assert( member );
440 if ( isUnnamedBitfield( dynamic_cast< ObjectDecl * > ( member ) ) ) {
441 // don't make a function whose parameter is an unnamed bitfield
442 continue;
443 } else if ( member->get_name() == "" ) {
444 // don't assign to anonymous members
445 // xxx - this is a temporary fix. Anonymous members tie into
446 // our inheritance model. I think the correct way to handle this is to
447 // cast the structure to the type of the member and let the resolver
448 // figure out whether it's valid/choose the correct unnamed member
449 continue;
450 }
451 memCtorType->get_parameters().push_back( new ObjectDecl( member->get_name(), Type::StorageClasses(), LinkageSpec::Cforall, 0, member->get_type()->clone(), 0 ) );
452 FunctionDecl * ctor = genFunc( "?{}", memCtorType->clone(), functionNesting );
453 makeStructFieldCtorBody( aggregateDecl->get_members().begin(), aggregateDecl->get_members().end(), ctor );
454 declsToAdd.push_back( ctor );
455 }
456 delete memCtorType;
457 }
458 }
459
460 /// generate a single union assignment expression (using memcpy)
461 template< typename OutputIterator >
462 void makeUnionFieldsAssignment( ObjectDecl * srcParam, ObjectDecl * dstParam, OutputIterator out ) {
463 UntypedExpr *copy = new UntypedExpr( new NameExpr( "__builtin_memcpy" ) );
464 copy->get_args().push_back( new AddressExpr( new VariableExpr( dstParam ) ) );
465 copy->get_args().push_back( new AddressExpr( new VariableExpr( srcParam ) ) );
466 copy->get_args().push_back( new SizeofExpr( srcParam->get_type()->clone() ) );
467 *out++ = new ExprStmt( noLabels, copy );
468 }
469
470 /// generates the body of a union assignment/copy constructor/field constructor
471 void makeUnionAssignBody( FunctionDecl * funcDecl ) {
472 FunctionType * ftype = funcDecl->get_functionType();
473 assert( ftype->get_parameters().size() == 2 );
474 ObjectDecl * dstParam = strict_dynamic_cast< ObjectDecl * >( ftype->get_parameters().front() );
475 ObjectDecl * srcParam = strict_dynamic_cast< ObjectDecl * >( ftype->get_parameters().back() );
476
477 makeUnionFieldsAssignment( srcParam, dstParam, back_inserter( funcDecl->get_statements()->get_kids() ) );
478 if ( CodeGen::isAssignment( funcDecl->get_name() ) ) {
479 // also generate return statement in assignment
480 funcDecl->get_statements()->get_kids().push_back( new ReturnStmt( noLabels, new VariableExpr( srcParam ) ) );
481 }
482 }
483
484 /// generates union constructors, destructors, and assignment operator
485 void makeUnionFunctions( UnionDecl *aggregateDecl, UnionInstType *refType, unsigned int functionNesting, std::list< Declaration * > & declsToAdd ) {
486 // Make function polymorphic in same parameters as generic union, if applicable
487 const std::list< TypeDecl* > & typeParams = aggregateDecl->get_parameters(); // List of type variables to be placed on the generated functions
488
489 // default ctor/dtor need only first parameter
490 // void ?{}(T *); void ^?{}(T *);
491 FunctionType *ctorType = genDefaultType( refType );
492 FunctionType *dtorType = genDefaultType( refType );
493
494 // copy ctor needs both parameters
495 // void ?{}(T *, T);
496 FunctionType *copyCtorType = genCopyType( refType );
497
498 // assignment needs both and return value
499 // T ?=?(T *, T);
500 FunctionType *assignType = genAssignType( refType );
501
502 cloneAll( typeParams, ctorType->get_forall() );
503 cloneAll( typeParams, dtorType->get_forall() );
504 cloneAll( typeParams, copyCtorType->get_forall() );
505 cloneAll( typeParams, assignType->get_forall() );
506
507 // add unused attribute to parameters of default constructor and destructor
508 ctorType->get_parameters().front()->get_attributes().push_back( new Attribute( "unused" ) );
509 dtorType->get_parameters().front()->get_attributes().push_back( new Attribute( "unused" ) );
510
511 // Routines at global scope marked "static" to prevent multiple definitions is separate translation units
512 // because each unit generates copies of the default routines for each aggregate.
513 FunctionDecl *assignDecl = genFunc( "?=?", assignType, functionNesting );
514 FunctionDecl *ctorDecl = genFunc( "?{}", ctorType, functionNesting );
515 FunctionDecl *copyCtorDecl = genFunc( "?{}", copyCtorType, functionNesting );
516 FunctionDecl *dtorDecl = genFunc( "^?{}", dtorType, functionNesting );
517
518 makeUnionAssignBody( assignDecl );
519
520 // body of assignment and copy ctor is the same
521 makeUnionAssignBody( copyCtorDecl );
522
523 // create a constructor which takes the first member type as a parameter.
524 // for example, for Union A { int x; double y; }; generate
525 // void ?{}(A *, int)
526 // This is to mimic C's behaviour which initializes the first member of the union.
527 std::list<Declaration *> memCtors;
528 for ( Declaration * member : aggregateDecl->get_members() ) {
529 if ( DeclarationWithType * field = dynamic_cast< DeclarationWithType * >( member ) ) {
530 ObjectDecl * srcParam = new ObjectDecl( "src", Type::StorageClasses(), LinkageSpec::Cforall, 0, field->get_type()->clone(), 0 );
531
532 FunctionType * memCtorType = ctorType->clone();
533 memCtorType->get_parameters().push_back( srcParam );
534 FunctionDecl * ctor = genFunc( "?{}", memCtorType, functionNesting );
535
536 makeUnionAssignBody( ctor );
537 memCtors.push_back( ctor );
538 // only generate a ctor for the first field
539 break;
540 }
541 }
542
543 declsToAdd.push_back( ctorDecl );
544 declsToAdd.push_back( copyCtorDecl );
545 declsToAdd.push_back( dtorDecl );
546 declsToAdd.push_back( assignDecl ); // assignment should come last since it uses copy constructor in return
547 declsToAdd.splice( declsToAdd.end(), memCtors );
548 }
549
550 AutogenerateRoutines::AutogenerateRoutines() {
551 // the order here determines the order that these functions are generated.
552 // assignment should come last since it uses copy constructor in return.
553 data.emplace_back( "?{}", genDefaultType, constructable );
554 data.emplace_back( "?{}", genCopyType, copyable );
555 data.emplace_back( "^?{}", genDefaultType, destructable );
556 data.emplace_back( "?=?", genAssignType, assignable );
557 }
558
559 void AutogenerateRoutines::previsit( EnumDecl * enumDecl ) {
560 visit_children = false;
561 if ( ! enumDecl->get_members().empty() ) {
562 EnumInstType *enumInst = new EnumInstType( Type::Qualifiers(), enumDecl->get_name() );
563 // enumInst->set_baseEnum( enumDecl );
564 makeEnumFunctions( enumInst, functionNesting, declsToAddAfter );
565 }
566 }
567
568 void AutogenerateRoutines::previsit( StructDecl * structDecl ) {
569 visit_children = false;
570 if ( structDecl->has_body() && structsDone.find( structDecl->name ) == structsDone.end() ) {
571 StructInstType structInst( Type::Qualifiers(), structDecl->name );
572 for ( TypeDecl * typeDecl : structDecl->parameters ) {
573 // need to visit assertions so that they are added to the appropriate maps
574 acceptAll( typeDecl->assertions, *visitor );
575 structInst.parameters.push_back( new TypeExpr( new TypeInstType( Type::Qualifiers(), typeDecl->name, typeDecl ) ) );
576 }
577 structInst.set_baseStruct( structDecl );
578 makeStructFunctions( structDecl, &structInst, functionNesting, declsToAddAfter, data );
579 structsDone.insert( structDecl->name );
580 } // if
581 }
582
583 void AutogenerateRoutines::previsit( UnionDecl * unionDecl ) {
584 visit_children = false;
585 if ( ! unionDecl->get_members().empty() ) {
586 UnionInstType unionInst( Type::Qualifiers(), unionDecl->get_name() );
587 unionInst.set_baseUnion( unionDecl );
588 for ( TypeDecl * typeDecl : unionDecl->get_parameters() ) {
589 unionInst.get_parameters().push_back( new TypeExpr( new TypeInstType( Type::Qualifiers(), typeDecl->get_name(), typeDecl ) ) );
590 }
591 makeUnionFunctions( unionDecl, &unionInst, functionNesting, declsToAddAfter );
592 } // if
593 }
594
595 Type * declToTypeDeclBase( Declaration * decl ) {
596 if ( TypeDecl * td = dynamic_cast< TypeDecl * >( decl ) ) {
597 return td->base;
598 }
599 return nullptr;
600 }
601
602 // generate ctor/dtors/assign for typedecls, e.g., otype T = int *;
603 void AutogenerateRoutines::previsit( TypeDecl * typeDecl ) {
604 visit_children = false;
605 if ( ! typeDecl->base ) return;
606
607 // generate each of the functions based on the supplied FuncData objects
608 std::list< FunctionDecl * > newFuncs;
609 std::list< Declaration * > tds { typeDecl };
610 std::list< TypeDecl * > typeParams;
611 TypeInstType refType( Type::Qualifiers(), typeDecl->name, typeDecl );
612 auto generator = makeFuncGenerator( lazy_map( tds, declToTypeDeclBase ), &refType, functionNesting, typeParams, back_inserter( newFuncs ) );
613 for ( const FuncData & d : data ) {
614 generator.gen( d, false );
615 }
616
617 if ( functionNesting == 0 ) {
618 // forward declare if top-level struct, so that
619 // type is complete as soon as its body ends
620 // Note: this is necessary if we want structs which contain
621 // generic (otype) structs as members.
622 for ( FunctionDecl * dcl : newFuncs ) {
623 addForwardDecl( dcl, declsToAddAfter );
624 }
625 }
626
627 for ( FunctionDecl * dcl : newFuncs ) {
628 FunctionType * ftype = dcl->type;
629 assertf( ftype->parameters.size() == 1 || ftype->parameters.size() == 2, "Incorrect number of parameters in autogenerated typedecl function: %zd", ftype->parameters.size() );
630 DeclarationWithType * dst = ftype->parameters.front();
631 DeclarationWithType * src = ftype->parameters.size() == 2 ? ftype->parameters.back() : nullptr;
632 // generate appropriate calls to member ctor, assignment
633 // destructor needs to do everything in reverse, so pass "forward" based on whether the function is a destructor
634 UntypedExpr * expr = new UntypedExpr( new NameExpr( dcl->name ) );
635 expr->args.push_back( new CastExpr( new VariableExpr( dst ), new ReferenceType( Type::Qualifiers(), typeDecl->base->clone() ) ) );
636 if ( src ) expr->args.push_back( new CastExpr( new VariableExpr( src ), typeDecl->base->clone() ) );
637 dcl->statements->kids.push_back( new ExprStmt( noLabels, expr ) );
638 if ( CodeGen::isAssignment( dcl->get_name() ) ) {
639 // assignment needs to return a value
640 FunctionType * assignType = dcl->type;
641 assert( assignType->parameters.size() == 2 );
642 ObjectDecl * srcParam = strict_dynamic_cast< ObjectDecl * >( assignType->parameters.back() );
643 dcl->statements->kids.push_back( new ReturnStmt( noLabels, new VariableExpr( srcParam ) ) );
644 }
645 declsToAddAfter.push_back( dcl );
646 }
647 }
648
649 void AutogenerateRoutines::previsit( FunctionType *) {
650 // ensure that we don't add assignment ops for types defined as part of the function
651 visit_children = false;
652 }
653
654 void AutogenerateRoutines::previsit( PointerType *) {
655 // ensure that we don't add assignment ops for types defined as part of the pointer
656 visit_children = false;
657 }
658
659 void AutogenerateRoutines::previsit( TraitDecl * ) {
660 // ensure that we don't add assignment ops for types defined as part of the trait
661 visit_children = false;
662 }
663
664 void AutogenerateRoutines::previsit( FunctionDecl * functionDecl ) {
665 visit_children = false;
666 // record the existence of this function as appropriate
667 insert( functionDecl, constructable, InitTweak::isDefaultConstructor );
668 insert( functionDecl, assignable, InitTweak::isAssignment );
669 insert( functionDecl, copyable, InitTweak::isCopyConstructor );
670 insert( functionDecl, destructable, InitTweak::isDestructor );
671
672 maybeAccept( functionDecl->type, *visitor );
673 functionNesting += 1;
674 maybeAccept( functionDecl->statements, *visitor );
675 functionNesting -= 1;
676 }
677
678 void AutogenerateRoutines::previsit( CompoundStmt * ) {
679 GuardScope( constructable );
680 GuardScope( assignable );
681 GuardScope( copyable );
682 GuardScope( destructable );
683 GuardScope( structsDone );
684 }
685
686 void makeTupleFunctionBody( FunctionDecl * function ) {
687 FunctionType * ftype = function->get_functionType();
688 assertf( ftype->get_parameters().size() == 1 || ftype->get_parameters().size() == 2, "too many parameters in generated tuple function" );
689
690 UntypedExpr * untyped = new UntypedExpr( new NameExpr( function->get_name() ) );
691
692 /// xxx - &* is used to make this easier for later passes to handle
693 untyped->get_args().push_back( new AddressExpr( UntypedExpr::createDeref( new VariableExpr( ftype->get_parameters().front() ) ) ) );
694 if ( ftype->get_parameters().size() == 2 ) {
695 untyped->get_args().push_back( new VariableExpr( ftype->get_parameters().back() ) );
696 }
697 function->get_statements()->get_kids().push_back( new ExprStmt( noLabels, untyped ) );
698 function->get_statements()->get_kids().push_back( new ReturnStmt( noLabels, UntypedExpr::createDeref( new VariableExpr( ftype->get_parameters().front() ) ) ) );
699 }
700
701 void AutogenTupleRoutines::postvisit( TupleType * tupleType ) {
702 std::string mangleName = SymTab::Mangler::mangleType( tupleType );
703 if ( seenTuples.find( mangleName ) != seenTuples.end() ) return;
704 seenTuples.insert( mangleName );
705
706 // T ?=?(T *, T);
707 FunctionType *assignType = genAssignType( tupleType );
708
709 // void ?{}(T *); void ^?{}(T *);
710 FunctionType *ctorType = genDefaultType( tupleType );
711 FunctionType *dtorType = genDefaultType( tupleType );
712
713 // void ?{}(T *, T);
714 FunctionType *copyCtorType = genCopyType( tupleType );
715
716 std::set< TypeDecl* > done;
717 std::list< TypeDecl * > typeParams;
718 for ( Type * t : *tupleType ) {
719 if ( TypeInstType * ty = dynamic_cast< TypeInstType * >( t ) ) {
720 if ( ! done.count( ty->get_baseType() ) ) {
721 TypeDecl * newDecl = new TypeDecl( ty->get_baseType()->get_name(), Type::StorageClasses(), nullptr, TypeDecl::Any );
722 TypeInstType * inst = new TypeInstType( Type::Qualifiers(), newDecl->get_name(), newDecl );
723 newDecl->get_assertions().push_back( new FunctionDecl( "?=?", Type::StorageClasses(), LinkageSpec::Cforall, genAssignType( inst ), nullptr,
724 std::list< Attribute * >(), Type::FuncSpecifiers( Type::Inline ) ) );
725 newDecl->get_assertions().push_back( new FunctionDecl( "?{}", Type::StorageClasses(), LinkageSpec::Cforall, genDefaultType( inst ), nullptr,
726 std::list< Attribute * >(), Type::FuncSpecifiers( Type::Inline ) ) );
727 newDecl->get_assertions().push_back( new FunctionDecl( "?{}", Type::StorageClasses(), LinkageSpec::Cforall, genCopyType( inst ), nullptr,
728 std::list< Attribute * >(), Type::FuncSpecifiers( Type::Inline ) ) );
729 newDecl->get_assertions().push_back( new FunctionDecl( "^?{}", Type::StorageClasses(), LinkageSpec::Cforall, genDefaultType( inst ), nullptr,
730 std::list< Attribute * >(), Type::FuncSpecifiers( Type::Inline ) ) );
731 typeParams.push_back( newDecl );
732 done.insert( ty->get_baseType() );
733 }
734 }
735 }
736 cloneAll( typeParams, ctorType->get_forall() );
737 cloneAll( typeParams, dtorType->get_forall() );
738 cloneAll( typeParams, copyCtorType->get_forall() );
739 cloneAll( typeParams, assignType->get_forall() );
740
741 FunctionDecl *assignDecl = genFunc( "?=?", assignType, functionNesting );
742 FunctionDecl *ctorDecl = genFunc( "?{}", ctorType, functionNesting );
743 FunctionDecl *copyCtorDecl = genFunc( "?{}", copyCtorType, functionNesting );
744 FunctionDecl *dtorDecl = genFunc( "^?{}", dtorType, functionNesting );
745
746 makeTupleFunctionBody( assignDecl );
747 makeTupleFunctionBody( ctorDecl );
748 makeTupleFunctionBody( copyCtorDecl );
749 makeTupleFunctionBody( dtorDecl );
750
751 declsToAddBefore.push_back( ctorDecl );
752 declsToAddBefore.push_back( copyCtorDecl );
753 declsToAddBefore.push_back( dtorDecl );
754 declsToAddBefore.push_back( assignDecl ); // assignment should come last since it uses copy constructor in return
755 }
756
757 void AutogenTupleRoutines::previsit( FunctionDecl *functionDecl ) {
758 visit_children = false;
759 maybeAccept( functionDecl->type, *visitor );
760 functionNesting += 1;
761 maybeAccept( functionDecl->statements, *visitor );
762 functionNesting -= 1;
763 }
764
765 void AutogenTupleRoutines::previsit( CompoundStmt * ) {
766 GuardScope( seenTuples );
767 }
768} // SymTab
769
770// Local Variables: //
771// tab-width: 4 //
772// mode: c++ //
773// compile-command: "make install" //
774// End: //
Note: See TracBrowser for help on using the repository browser.