source: src/SymTab/Autogen.cc@ 22bc276

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

Convert AutogenerateRoutines to PassVisitor

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