source: src/SymTab/Autogen.cc@ 0698aa1

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

Merge branch 'master' into references

  • Property mode set to 100644
File size: 36.8 KB
Line 
1//
2// Cforall Version 1.0.0 Copyright (C) 2015 University of Waterloo
3//
4// The contents of this file are covered under the licence agreement in the
5// file "LICENCE" distributed with Cforall.
6//
7// Autogen.cc --
8//
9// Author : Rob Schluntz
10// Created On : Thu Mar 03 15:45:56 2016
11// Last Modified By : Andrew Beach
12// Last Modified On : Wed Jun 28 15:30:00 2017
13// Update Count : 61
14//
15
16#include <list>
17#include <iterator>
18#include "SynTree/Visitor.h"
19#include "SynTree/Type.h"
20#include "SynTree/Statement.h"
21#include "SynTree/TypeSubstitution.h"
22#include "Common/utility.h"
23#include "AddVisit.h"
24#include "MakeLibCfa.h"
25#include "Autogen.h"
26#include "GenPoly/ScopedSet.h"
27#include "Common/ScopedMap.h"
28#include "SymTab/Mangler.h"
29#include "GenPoly/DeclMutator.h"
30
31namespace SymTab {
32 Type * SizeType = 0;
33 typedef ScopedMap< std::string, bool > TypeMap;
34
35 /// 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.
36 struct FuncData {
37 typedef FunctionType * (*TypeGen)( Type * );
38 FuncData( const std::string & fname, const TypeGen & genType, TypeMap & map ) : fname( fname ), genType( genType ), map( map ) {}
39 std::string fname;
40 TypeGen genType;
41 TypeMap & map;
42 };
43
44 class AutogenerateRoutines final : public Visitor {
45 template< typename Visitor >
46 friend void acceptAndAdd( std::list< Declaration * > &translationUnit, Visitor &visitor );
47 template< typename Visitor >
48 friend void addVisitStatementList( std::list< Statement* > &stmts, Visitor &visitor );
49 public:
50 std::list< Declaration * > &get_declsToAdd() { return declsToAdd; }
51
52 typedef Visitor Parent;
53 using Parent::visit;
54
55 AutogenerateRoutines();
56
57 virtual void visit( EnumDecl *enumDecl );
58 virtual void visit( StructDecl *structDecl );
59 virtual void visit( UnionDecl *structDecl );
60 virtual void visit( TypeDecl *typeDecl );
61 virtual void visit( TraitDecl *ctxDecl );
62 virtual void visit( FunctionDecl *functionDecl );
63
64 virtual void visit( FunctionType *ftype );
65 virtual void visit( PointerType *ftype );
66
67 virtual void visit( CompoundStmt *compoundStmt );
68 virtual void visit( SwitchStmt *switchStmt );
69
70 private:
71 template< typename StmtClass > void visitStatement( StmtClass *stmt );
72
73 std::list< Declaration * > declsToAdd, declsToAddAfter;
74 std::set< std::string > structsDone;
75 unsigned int functionNesting = 0; // current level of nested functions
76 /// Note: the following maps could be ScopedSets, but it should be easier to work
77 /// deleted functions in if they are maps, since the value false can be inserted
78 /// at the current scope without affecting outer scopes or requiring copies.
79 TypeMap copyable, assignable, constructable, destructable;
80 std::vector< FuncData > data;
81 };
82
83 /// generates routines for tuple types.
84 /// Doesn't really need to be a mutator, but it's easier to reuse DeclMutator than it is to use AddVisit
85 /// or anything we currently have that supports adding new declarations for visitors
86 class AutogenTupleRoutines : public GenPoly::DeclMutator {
87 public:
88 typedef GenPoly::DeclMutator Parent;
89 using Parent::mutate;
90
91 virtual DeclarationWithType * mutate( FunctionDecl *functionDecl );
92
93 virtual Type * mutate( TupleType *tupleType );
94
95 virtual CompoundStmt * mutate( CompoundStmt *compoundStmt );
96
97 private:
98 unsigned int functionNesting = 0; // current level of nested functions
99 GenPoly::ScopedSet< std::string > seenTuples;
100 };
101
102 void autogenerateRoutines( std::list< Declaration * > &translationUnit ) {
103 AutogenerateRoutines generator;
104 acceptAndAdd( translationUnit, generator );
105
106 // needs to be done separately because AutogenerateRoutines skips types that appear as function arguments, etc.
107 // AutogenTupleRoutines tupleGenerator;
108 // tupleGenerator.mutateDeclarationList( translationUnit );
109 }
110
111 bool isUnnamedBitfield( ObjectDecl * obj ) {
112 return obj != NULL && obj->get_name() == "" && obj->get_bitfieldWidth() != NULL;
113 }
114
115 /// inserts a forward declaration for functionDecl into declsToAdd
116 void addForwardDecl( FunctionDecl * functionDecl, std::list< Declaration * > & declsToAdd ) {
117 FunctionDecl * decl = functionDecl->clone();
118 delete decl->get_statements();
119 decl->set_statements( NULL );
120 declsToAdd.push_back( decl );
121 decl->fixUniqueId();
122 }
123
124 /// given type T, generate type of default ctor/dtor, i.e. function type void (*) (T *)
125 FunctionType * genDefaultType( Type * paramType ) {
126 FunctionType *ftype = new FunctionType( Type::Qualifiers(), false );
127 ObjectDecl *dstParam = new ObjectDecl( "_dst", Type::StorageClasses(), LinkageSpec::Cforall, nullptr, new PointerType( Type::Qualifiers(), paramType->clone() ), nullptr );
128 ftype->get_parameters().push_back( dstParam );
129
130 return ftype;
131 }
132
133 /// given type T, generate type of copy ctor, i.e. function type void (*) (T *, T)
134 FunctionType * genCopyType( Type * paramType ) {
135 FunctionType *ftype = genDefaultType( paramType );
136 ObjectDecl *srcParam = new ObjectDecl( "_src", Type::StorageClasses(), LinkageSpec::Cforall, nullptr, paramType->clone(), nullptr );
137 ftype->get_parameters().push_back( srcParam );
138 return ftype;
139 }
140
141 /// given type T, generate type of assignment, i.e. function type T (*) (T *, T)
142 FunctionType * genAssignType( Type * paramType ) {
143 FunctionType *ftype = genCopyType( paramType );
144 ObjectDecl *returnVal = new ObjectDecl( "_ret", Type::StorageClasses(), LinkageSpec::Cforall, nullptr, paramType->clone(), nullptr );
145 ftype->get_returnVals().push_back( returnVal );
146 return ftype;
147 }
148
149 /// true if the aggregate's layout is dynamic
150 template< typename AggrDecl >
151 bool hasDynamicLayout( AggrDecl * aggregateDecl ) {
152 for ( TypeDecl * param : aggregateDecl->get_parameters() ) {
153 if ( param->isComplete() ) return true;
154 }
155 return false;
156 }
157
158 /// generate a function decl from a name and type. Nesting depth determines whether
159 /// the declaration is static or not; optional paramter determines if declaration is intrinsic
160 FunctionDecl * genFunc( const std::string & fname, FunctionType * ftype, unsigned int functionNesting, bool isIntrinsic = false ) {
161 // Routines at global scope marked "static" to prevent multiple definitions in separate translation units
162 // because each unit generates copies of the default routines for each aggregate.
163// DeclarationNode::StorageClass sc = functionNesting > 0 ? DeclarationNode::NoStorageClass : DeclarationNode::Static;
164 Type::StorageClasses scs = functionNesting > 0 ? Type::StorageClasses() : Type::StorageClasses( Type::Static );
165 LinkageSpec::Spec spec = isIntrinsic ? LinkageSpec::Intrinsic : LinkageSpec::AutoGen;
166 FunctionDecl * decl = new FunctionDecl( fname, scs, spec, ftype, new CompoundStmt( noLabels ),
167 std::list< Attribute * >(), Type::FuncSpecifiers( Type::Inline ) );
168 decl->fixUniqueId();
169 return decl;
170 }
171
172 /// inserts base type of first argument into map if pred(funcDecl) is true
173 void insert( FunctionDecl *funcDecl, TypeMap & map, FunctionDecl * (*pred)(Declaration *) ) {
174 // insert type into constructable, etc. map if appropriate
175 if ( pred( funcDecl ) ) {
176 FunctionType * ftype = funcDecl->get_functionType();
177 assert( ! ftype->get_parameters().empty() );
178 Type * t = InitTweak::getPointerBase( ftype->get_parameters().front()->get_type() );
179 assert( t );
180 map.insert( Mangler::mangleType( t ), true );
181 }
182 }
183
184 /// using map and t, determines if is constructable, etc.
185 bool lookup( const TypeMap & map, Type * t ) {
186 if ( dynamic_cast< PointerType * >( t ) ) {
187 // will need more complicated checking if we want this to work with pointer types, since currently
188 return true;
189 } else if ( ArrayType * at = dynamic_cast< ArrayType * >( t ) ) {
190 // an array's constructor, etc. is generated on the fly based on the base type's constructor, etc.
191 return lookup( map, at->get_base() );
192 }
193 TypeMap::const_iterator it = map.find( Mangler::mangleType( t ) );
194 if ( it != map.end() ) return it->second;
195 // something that does not appear in the map is by default not constructable, etc.
196 return false;
197 }
198
199 /// using map and aggr, examines each member to determine if constructor, etc. should be generated
200 template<typename AggrDecl>
201 bool shouldGenerate( const TypeMap & map, AggrDecl * aggr ) {
202 for ( Declaration * dcl : aggr->get_members() ) {
203 if ( DeclarationWithType * dwt = dynamic_cast< DeclarationWithType * >( dcl ) ) {
204 if ( ! lookup( map, dwt->get_type() ) ) return false;
205 }
206 }
207 return true;
208 }
209
210 /// data structure for abstracting the generation of special functions
211 template< typename OutputIterator >
212 struct FuncGenerator {
213 StructDecl *aggregateDecl;
214 StructInstType *refType;
215 unsigned int functionNesting;
216 const std::list< TypeDecl* > & typeParams;
217 OutputIterator out;
218 FuncGenerator( StructDecl *aggregateDecl, StructInstType *refType, unsigned int functionNesting, const std::list< TypeDecl* > & typeParams, OutputIterator out ) : aggregateDecl( aggregateDecl ), refType( refType ), functionNesting( functionNesting ), typeParams( typeParams ), out( out ) {}
219
220 /// generates a function (?{}, ?=?, ^?{}) based on the data argument and members. If function is generated, inserts the type into the map.
221 void gen( const FuncData & data, bool concurrent_type ) {
222 if ( ! shouldGenerate( data.map, aggregateDecl ) ) return;
223 FunctionType * ftype = data.genType( refType );
224
225 if(concurrent_type && InitTweak::isDestructor( data.fname )) {
226 ftype->get_parameters().front()->get_type()->set_mutex( true );
227 }
228
229 cloneAll( typeParams, ftype->get_forall() );
230 *out++ = genFunc( data.fname, ftype, functionNesting );
231 data.map.insert( Mangler::mangleType( refType ), true );
232 }
233 };
234
235 template< typename OutputIterator >
236 FuncGenerator<OutputIterator> makeFuncGenerator( StructDecl *aggregateDecl, StructInstType *refType, unsigned int functionNesting, const std::list< TypeDecl* > & typeParams, OutputIterator out ) {
237 return FuncGenerator<OutputIterator>( aggregateDecl, refType, functionNesting, typeParams, out );
238 }
239
240 /// generates a single enumeration assignment expression
241 ApplicationExpr * genEnumAssign( FunctionType * ftype, FunctionDecl * assignDecl ) {
242 // enum copy construct and assignment is just C-style assignment.
243 // this looks like a bad recursive call, but code gen will turn it into
244 // a C-style assignment.
245 // This happens before function pointer type conversion, so need to do it manually here
246 // NOTE: ftype is not necessarily the functionType belonging to assignDecl - ftype is the
247 // type of the function that this expression is being generated for (so that the correct
248 // parameters) are using in the variable exprs
249 assert( ftype->get_parameters().size() == 2 );
250 ObjectDecl * dstParam = safe_dynamic_cast< ObjectDecl * >( ftype->get_parameters().front() );
251 ObjectDecl * srcParam = safe_dynamic_cast< ObjectDecl * >( ftype->get_parameters().back() );
252
253 VariableExpr * assignVarExpr = new VariableExpr( assignDecl );
254 Type * assignVarExprType = assignVarExpr->get_result();
255 assignVarExprType = new PointerType( Type::Qualifiers(), assignVarExprType );
256 assignVarExpr->set_result( assignVarExprType );
257 ApplicationExpr * assignExpr = new ApplicationExpr( assignVarExpr );
258 assignExpr->get_args().push_back( new VariableExpr( dstParam ) );
259 assignExpr->get_args().push_back( new VariableExpr( srcParam ) );
260 return assignExpr;
261 }
262
263 // E ?=?(E volatile*, int),
264 // ?=?(E _Atomic volatile*, int);
265 void makeEnumFunctions( EnumInstType *refType, unsigned int functionNesting, std::list< Declaration * > &declsToAdd ) {
266
267 // T ?=?(E *, E);
268 FunctionType *assignType = genAssignType( refType );
269
270 // void ?{}(E *); void ^?{}(E *);
271 FunctionType * ctorType = genDefaultType( refType->clone() );
272 FunctionType * dtorType = genDefaultType( refType->clone() );
273
274 // void ?{}(E *, E);
275 FunctionType *copyCtorType = genCopyType( refType->clone() );
276
277 // xxx - should we also generate void ?{}(E *, int) and E ?{}(E *, E)?
278 // right now these cases work, but that might change.
279
280 // xxx - Temporary: make these functions intrinsic so they codegen as C assignment.
281 // Really they're something of a cross between instrinsic and autogen, so should
282 // probably make a new linkage type
283 FunctionDecl *assignDecl = genFunc( "?=?", assignType, functionNesting, true );
284 FunctionDecl *ctorDecl = genFunc( "?{}", ctorType, functionNesting, true );
285 FunctionDecl *copyCtorDecl = genFunc( "?{}", copyCtorType, functionNesting, true );
286 FunctionDecl *dtorDecl = genFunc( "^?{}", dtorType, functionNesting, true );
287
288 // body is either return stmt or expr stmt
289 assignDecl->get_statements()->get_kids().push_back( new ReturnStmt( noLabels, genEnumAssign( assignType, assignDecl ) ) );
290 copyCtorDecl->get_statements()->get_kids().push_back( new ExprStmt( noLabels, genEnumAssign( copyCtorType, assignDecl ) ) );
291
292 declsToAdd.push_back( ctorDecl );
293 declsToAdd.push_back( copyCtorDecl );
294 declsToAdd.push_back( dtorDecl );
295 declsToAdd.push_back( assignDecl ); // assignment should come last since it uses copy constructor in return
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 isDynamicLayout, bool forward = true ) {
300 ObjectDecl * returnVal = NULL;
301 if ( ! func->get_functionType()->get_returnVals().empty() ) {
302 returnVal = dynamic_cast<ObjectDecl*>( func->get_functionType()->get_returnVals().front() );
303 }
304
305 InitTweak::InitExpander srcParam( src );
306
307 // assign to destination (and return value if generic)
308 UntypedExpr *derefExpr = UntypedExpr::createDeref( new VariableExpr( dstParam ) );
309 Expression *dstselect = new MemberExpr( field, derefExpr );
310 genImplicitCall( srcParam, dstselect, func->get_name(), back_inserter( func->get_statements()->get_kids() ), field, forward );
311
312 if ( isDynamicLayout && returnVal ) {
313 // xxx - there used to be a dereference on returnVal, but this seems to have been wrong?
314 Expression *retselect = new MemberExpr( field, new VariableExpr( returnVal ) );
315 genImplicitCall( srcParam, retselect, func->get_name(), back_inserter( func->get_statements()->get_kids() ), field, forward );
316 } // if
317 }
318
319 /// 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
320 template<typename Iterator>
321 void makeStructFunctionBody( Iterator member, Iterator end, FunctionDecl * func, bool isDynamicLayout, bool forward = true ) {
322 for ( ; member != end; ++member ) {
323 if ( DeclarationWithType *field = dynamic_cast< DeclarationWithType * >( *member ) ) { // otherwise some form of type declaration, e.g. Aggregate
324 // query the type qualifiers of this field and skip assigning it if it is marked const.
325 // If it is an array type, we need to strip off the array layers to find its qualifiers.
326 Type * type = field->get_type();
327 while ( ArrayType * at = dynamic_cast< ArrayType * >( type ) ) {
328 type = at->get_base();
329 }
330
331 if ( type->get_const() && func->get_name() == "?=?" ) {
332 // don't assign const members, but do construct/destruct
333 continue;
334 }
335
336 if ( field->get_name() == "" ) {
337 // don't assign to anonymous members
338 // xxx - this is a temporary fix. Anonymous members tie into
339 // our inheritance model. I think the correct way to handle this is to
340 // cast the structure to the type of the member and let the resolver
341 // figure out whether it's valid and have a pass afterwards that fixes
342 // the assignment to use pointer arithmetic with the offset of the
343 // member, much like how generic type members are handled.
344 continue;
345 }
346
347 assert( ! func->get_functionType()->get_parameters().empty() );
348 ObjectDecl * dstParam = dynamic_cast<ObjectDecl*>( func->get_functionType()->get_parameters().front() );
349 ObjectDecl * srcParam = NULL;
350 if ( func->get_functionType()->get_parameters().size() == 2 ) {
351 srcParam = dynamic_cast<ObjectDecl*>( func->get_functionType()->get_parameters().back() );
352 }
353 // srcParam may be NULL, in which case we have default ctor/dtor
354 assert( dstParam );
355
356 Expression *srcselect = srcParam ? new MemberExpr( field, new VariableExpr( srcParam ) ) : NULL;
357 makeStructMemberOp( dstParam, srcselect, field, func, isDynamicLayout, forward );
358 } // if
359 } // for
360 } // makeStructFunctionBody
361
362 /// generate the body of a constructor which takes parameters that match fields, e.g.
363 /// void ?{}(A *, int) and void?{}(A *, int, int) for a struct A which has two int fields.
364 template<typename Iterator>
365 void makeStructFieldCtorBody( Iterator member, Iterator end, FunctionDecl * func, bool isDynamicLayout ) {
366 FunctionType * ftype = func->get_functionType();
367 std::list<DeclarationWithType*> & params = ftype->get_parameters();
368 assert( params.size() >= 2 ); // should not call this function for default ctor, etc.
369
370 // skip 'this' parameter
371 ObjectDecl * dstParam = dynamic_cast<ObjectDecl*>( params.front() );
372 assert( dstParam );
373 std::list<DeclarationWithType*>::iterator parameter = params.begin()+1;
374 for ( ; member != end; ++member ) {
375 if ( DeclarationWithType * field = dynamic_cast<DeclarationWithType*>( *member ) ) {
376 if ( isUnnamedBitfield( dynamic_cast< ObjectDecl * > ( field ) ) ) {
377 // don't make a function whose parameter is an unnamed bitfield
378 continue;
379 } else if ( field->get_name() == "" ) {
380 // don't assign to anonymous members
381 // xxx - this is a temporary fix. Anonymous members tie into
382 // our inheritance model. I think the correct way to handle this is to
383 // cast the structure to the type of the member and let the resolver
384 // figure out whether it's valid and have a pass afterwards that fixes
385 // the assignment to use pointer arithmetic with the offset of the
386 // member, much like how generic type members are handled.
387 continue;
388 } else if ( parameter != params.end() ) {
389 // matching parameter, initialize field with copy ctor
390 Expression *srcselect = new VariableExpr(*parameter);
391 makeStructMemberOp( dstParam, srcselect, field, func, isDynamicLayout );
392 ++parameter;
393 } else {
394 // no matching parameter, initialize field with default ctor
395 makeStructMemberOp( dstParam, NULL, field, func, isDynamicLayout );
396 }
397 }
398 }
399 }
400
401 /// generates struct constructors, destructor, and assignment functions
402 void makeStructFunctions( StructDecl *aggregateDecl, StructInstType *refType, unsigned int functionNesting, std::list< Declaration * > & declsToAdd, const std::vector< FuncData > & data ) {
403 // Builtins do not use autogeneration.
404 if ( aggregateDecl->get_linkage() == LinkageSpec::Builtin ||
405 aggregateDecl->get_linkage() == LinkageSpec::BuiltinC ) {
406 return;
407 }
408
409 // Make function polymorphic in same parameters as generic struct, if applicable
410 const std::list< TypeDecl* > & typeParams = aggregateDecl->get_parameters(); // List of type variables to be placed on the generated functions
411 bool isDynamicLayout = hasDynamicLayout( aggregateDecl ); // NOTE this flag is an incredibly ugly kludge; we should fix the assignment signature instead (ditto for union)
412
413 // generate each of the functions based on the supplied FuncData objects
414 std::list< FunctionDecl * > newFuncs;
415 auto generator = makeFuncGenerator( aggregateDecl, refType, functionNesting, typeParams, back_inserter( newFuncs ) );
416 for ( const FuncData & d : data ) {
417 generator.gen( d, aggregateDecl->is_thread() || aggregateDecl->is_monitor() );
418 }
419
420 // field ctors are only generated if default constructor and copy constructor are both generated
421 unsigned numCtors = std::count_if( newFuncs.begin(), newFuncs.end(), [](FunctionDecl * dcl) { return InitTweak::isConstructor( dcl->get_name() ); } );
422
423 if ( functionNesting == 0 ) {
424 // forward declare if top-level struct, so that
425 // type is complete as soon as its body ends
426 // Note: this is necessary if we want structs which contain
427 // generic (otype) structs as members.
428 for ( FunctionDecl * dcl : newFuncs ) {
429 addForwardDecl( dcl, declsToAdd );
430 }
431 }
432
433 for ( FunctionDecl * dcl : newFuncs ) {
434 // generate appropriate calls to member ctor, assignment
435 // destructor needs to do everything in reverse, so pass "forward" based on whether the function is a destructor
436 if ( ! InitTweak::isDestructor( dcl->get_name() ) ) {
437 makeStructFunctionBody( aggregateDecl->get_members().begin(), aggregateDecl->get_members().end(), dcl, isDynamicLayout );
438 } else {
439 makeStructFunctionBody( aggregateDecl->get_members().rbegin(), aggregateDecl->get_members().rend(), dcl, isDynamicLayout, false );
440 }
441 if ( InitTweak::isAssignment( dcl->get_name() ) ) {
442 // assignment needs to return a value
443 FunctionType * assignType = dcl->get_functionType();
444 assert( assignType->get_parameters().size() == 2 );
445 ObjectDecl * srcParam = safe_dynamic_cast< ObjectDecl * >( assignType->get_parameters().back() );
446 dcl->get_statements()->get_kids().push_back( new ReturnStmt( noLabels, new VariableExpr( srcParam ) ) );
447 }
448 declsToAdd.push_back( dcl );
449 }
450
451 // create constructors which take each member type as a parameter.
452 // for example, for struct A { int x, y; }; generate
453 // void ?{}(A *, int) and void ?{}(A *, int, int)
454 // Field constructors are only generated if default and copy constructor
455 // are generated, since they need access to both
456 if ( numCtors == 2 ) {
457 FunctionType * memCtorType = genDefaultType( refType );
458 cloneAll( typeParams, memCtorType->get_forall() );
459 for ( std::list<Declaration *>::iterator i = aggregateDecl->get_members().begin(); i != aggregateDecl->get_members().end(); ++i ) {
460 DeclarationWithType * member = dynamic_cast<DeclarationWithType *>( *i );
461 assert( member );
462 if ( isUnnamedBitfield( dynamic_cast< ObjectDecl * > ( member ) ) ) {
463 // don't make a function whose parameter is an unnamed bitfield
464 continue;
465 } else if ( member->get_name() == "" ) {
466 // don't assign to anonymous members
467 // xxx - this is a temporary fix. Anonymous members tie into
468 // our inheritance model. I think the correct way to handle this is to
469 // cast the structure to the type of the member and let the resolver
470 // figure out whether it's valid and have a pass afterwards that fixes
471 // the assignment to use pointer arithmetic with the offset of the
472 // member, much like how generic type members are handled.
473 continue;
474 }
475 memCtorType->get_parameters().push_back( new ObjectDecl( member->get_name(), Type::StorageClasses(), LinkageSpec::Cforall, 0, member->get_type()->clone(), 0 ) );
476 FunctionDecl * ctor = genFunc( "?{}", memCtorType->clone(), functionNesting );
477 makeStructFieldCtorBody( aggregateDecl->get_members().begin(), aggregateDecl->get_members().end(), ctor, isDynamicLayout );
478 declsToAdd.push_back( ctor );
479 }
480 delete memCtorType;
481 }
482 }
483
484 /// generate a single union assignment expression (using memcpy)
485 template< typename OutputIterator >
486 void makeUnionFieldsAssignment( ObjectDecl * srcParam, ObjectDecl * dstParam, OutputIterator out ) {
487 UntypedExpr *copy = new UntypedExpr( new NameExpr( "__builtin_memcpy" ) );
488 copy->get_args().push_back( new VariableExpr( dstParam ) );
489 copy->get_args().push_back( new AddressExpr( new VariableExpr( srcParam ) ) );
490 copy->get_args().push_back( new SizeofExpr( srcParam->get_type()->clone() ) );
491 *out++ = new ExprStmt( noLabels, copy );
492 }
493
494 /// generates the body of a union assignment/copy constructor/field constructor
495 void makeUnionAssignBody( FunctionDecl * funcDecl ) {
496 FunctionType * ftype = funcDecl->get_functionType();
497 assert( ftype->get_parameters().size() == 2 );
498 ObjectDecl * dstParam = safe_dynamic_cast< ObjectDecl * >( ftype->get_parameters().front() );
499 ObjectDecl * srcParam = safe_dynamic_cast< ObjectDecl * >( ftype->get_parameters().back() );
500 ObjectDecl * returnVal = nullptr;
501 if ( ! ftype->get_returnVals().empty() ) {
502 returnVal = safe_dynamic_cast< ObjectDecl * >( ftype->get_returnVals().front() );
503 }
504
505 makeUnionFieldsAssignment( srcParam, dstParam, back_inserter( funcDecl->get_statements()->get_kids() ) );
506 if ( returnVal ) {
507 funcDecl->get_statements()->get_kids().push_back( new ReturnStmt( noLabels, new VariableExpr( srcParam ) ) );
508 }
509 }
510
511 /// generates union constructors, destructors, and assignment operator
512 void makeUnionFunctions( UnionDecl *aggregateDecl, UnionInstType *refType, unsigned int functionNesting, std::list< Declaration * > & declsToAdd ) {
513 // Make function polymorphic in same parameters as generic union, if applicable
514 const std::list< TypeDecl* > & typeParams = aggregateDecl->get_parameters(); // List of type variables to be placed on the generated functions
515
516 // default ctor/dtor need only first parameter
517 // void ?{}(T *); void ^?{}(T *);
518 FunctionType *ctorType = genDefaultType( refType );
519 FunctionType *dtorType = genDefaultType( refType );
520
521 // copy ctor needs both parameters
522 // void ?{}(T *, T);
523 FunctionType *copyCtorType = genCopyType( refType );
524
525 // assignment needs both and return value
526 // T ?=?(T *, T);
527 FunctionType *assignType = genAssignType( refType );
528
529 cloneAll( typeParams, ctorType->get_forall() );
530 cloneAll( typeParams, dtorType->get_forall() );
531 cloneAll( typeParams, copyCtorType->get_forall() );
532 cloneAll( typeParams, assignType->get_forall() );
533
534 // Routines at global scope marked "static" to prevent multiple definitions is separate translation units
535 // because each unit generates copies of the default routines for each aggregate.
536 FunctionDecl *assignDecl = genFunc( "?=?", assignType, functionNesting );
537 FunctionDecl *ctorDecl = genFunc( "?{}", ctorType, functionNesting );
538 FunctionDecl *copyCtorDecl = genFunc( "?{}", copyCtorType, functionNesting );
539 FunctionDecl *dtorDecl = genFunc( "^?{}", dtorType, functionNesting );
540
541 makeUnionAssignBody( assignDecl );
542
543 // body of assignment and copy ctor is the same
544 makeUnionAssignBody( copyCtorDecl );
545
546 // create a constructor which takes the first member type as a parameter.
547 // for example, for Union A { int x; double y; }; generate
548 // void ?{}(A *, int)
549 // This is to mimic C's behaviour which initializes the first member of the union.
550 std::list<Declaration *> memCtors;
551 for ( Declaration * member : aggregateDecl->get_members() ) {
552 if ( DeclarationWithType * field = dynamic_cast< DeclarationWithType * >( member ) ) {
553 ObjectDecl * srcParam = new ObjectDecl( "src", Type::StorageClasses(), LinkageSpec::Cforall, 0, field->get_type()->clone(), 0 );
554
555 FunctionType * memCtorType = ctorType->clone();
556 memCtorType->get_parameters().push_back( srcParam );
557 FunctionDecl * ctor = genFunc( "?{}", memCtorType, functionNesting );
558
559 makeUnionAssignBody( ctor );
560 memCtors.push_back( ctor );
561 // only generate a ctor for the first field
562 break;
563 }
564 }
565
566 declsToAdd.push_back( ctorDecl );
567 declsToAdd.push_back( copyCtorDecl );
568 declsToAdd.push_back( dtorDecl );
569 declsToAdd.push_back( assignDecl ); // assignment should come last since it uses copy constructor in return
570 declsToAdd.splice( declsToAdd.end(), memCtors );
571 }
572
573 AutogenerateRoutines::AutogenerateRoutines() {
574 // the order here determines the order that these functions are generated.
575 // assignment should come last since it uses copy constructor in return.
576 data.push_back( FuncData( "?{}", genDefaultType, constructable ) );
577 data.push_back( FuncData( "?{}", genCopyType, copyable ) );
578 data.push_back( FuncData( "^?{}", genDefaultType, destructable ) );
579 data.push_back( FuncData( "?=?", genAssignType, assignable ) );
580 }
581
582 void AutogenerateRoutines::visit( EnumDecl *enumDecl ) {
583 if ( ! enumDecl->get_members().empty() ) {
584 EnumInstType *enumInst = new EnumInstType( Type::Qualifiers(), enumDecl->get_name() );
585 // enumInst->set_baseEnum( enumDecl );
586 makeEnumFunctions( enumInst, functionNesting, declsToAddAfter );
587 }
588 }
589
590 void AutogenerateRoutines::visit( StructDecl *structDecl ) {
591 if ( structDecl->has_body() && structsDone.find( structDecl->get_name() ) == structsDone.end() ) {
592 StructInstType structInst( Type::Qualifiers(), structDecl->get_name() );
593 for ( TypeDecl * typeDecl : structDecl->get_parameters() ) {
594 // need to visit assertions so that they are added to the appropriate maps
595 acceptAll( typeDecl->get_assertions(), *this );
596 structInst.get_parameters().push_back( new TypeExpr( new TypeInstType( Type::Qualifiers(), typeDecl->get_name(), typeDecl ) ) );
597 }
598 structInst.set_baseStruct( structDecl );
599 makeStructFunctions( structDecl, &structInst, functionNesting, declsToAddAfter, data );
600 structsDone.insert( structDecl->get_name() );
601 } // if
602 }
603
604 void AutogenerateRoutines::visit( UnionDecl *unionDecl ) {
605 if ( ! unionDecl->get_members().empty() ) {
606 UnionInstType unionInst( Type::Qualifiers(), unionDecl->get_name() );
607 unionInst.set_baseUnion( unionDecl );
608 for ( TypeDecl * typeDecl : unionDecl->get_parameters() ) {
609 unionInst.get_parameters().push_back( new TypeExpr( new TypeInstType( Type::Qualifiers(), typeDecl->get_name(), typeDecl ) ) );
610 }
611 makeUnionFunctions( unionDecl, &unionInst, functionNesting, declsToAddAfter );
612 } // if
613 }
614
615 void AutogenerateRoutines::visit( TypeDecl *typeDecl ) {
616 TypeInstType *typeInst = new TypeInstType( Type::Qualifiers(), typeDecl->get_name(), false );
617 typeInst->set_baseType( typeDecl );
618 ObjectDecl *src = new ObjectDecl( "_src", Type::StorageClasses(), LinkageSpec::Cforall, nullptr, typeInst->clone(), nullptr );
619 ObjectDecl *dst = new ObjectDecl( "_dst", Type::StorageClasses(), LinkageSpec::Cforall, nullptr, new PointerType( Type::Qualifiers(), typeInst->clone() ), nullptr );
620
621 std::list< Statement * > stmts;
622 if ( typeDecl->get_base() ) {
623 // xxx - generate ctor/dtors for typedecls, e.g.
624 // otype T = int *;
625 UntypedExpr *assign = new UntypedExpr( new NameExpr( "?=?" ) );
626 assign->get_args().push_back( new CastExpr( new VariableExpr( dst ), new PointerType( Type::Qualifiers(), typeDecl->get_base()->clone() ) ) );
627 assign->get_args().push_back( new CastExpr( new VariableExpr( src ), typeDecl->get_base()->clone() ) );
628 stmts.push_back( new ReturnStmt( std::list< Label >(), assign ) );
629 } // if
630 FunctionType *type = new FunctionType( Type::Qualifiers(), false );
631 type->get_returnVals().push_back( new ObjectDecl( "", Type::StorageClasses(), LinkageSpec::Cforall, 0, typeInst, 0 ) );
632 type->get_parameters().push_back( dst );
633 type->get_parameters().push_back( src );
634 FunctionDecl *func = genFunc( "?=?", type, functionNesting );
635 func->get_statements()->get_kids() = stmts;
636 declsToAddAfter.push_back( func );
637 }
638
639 void addDecls( std::list< Declaration * > &declsToAdd, std::list< Statement * > &statements, std::list< Statement * >::iterator i ) {
640 for ( std::list< Declaration * >::iterator decl = declsToAdd.begin(); decl != declsToAdd.end(); ++decl ) {
641 statements.insert( i, new DeclStmt( noLabels, *decl ) );
642 } // for
643 declsToAdd.clear();
644 }
645
646 void AutogenerateRoutines::visit( FunctionType *) {
647 // ensure that we don't add assignment ops for types defined as part of the function
648 }
649
650 void AutogenerateRoutines::visit( PointerType *) {
651 // ensure that we don't add assignment ops for types defined as part of the pointer
652 }
653
654 void AutogenerateRoutines::visit( TraitDecl *) {
655 // ensure that we don't add assignment ops for types defined as part of the trait
656 }
657
658 template< typename StmtClass >
659 inline void AutogenerateRoutines::visitStatement( StmtClass *stmt ) {
660 std::set< std::string > oldStructs = structsDone;
661 addVisit( stmt, *this );
662 structsDone = oldStructs;
663 }
664
665 void AutogenerateRoutines::visit( FunctionDecl *functionDecl ) {
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->get_functionType(), *this );
673 functionNesting += 1;
674 maybeAccept( functionDecl->get_statements(), *this );
675 functionNesting -= 1;
676 }
677
678 void AutogenerateRoutines::visit( CompoundStmt *compoundStmt ) {
679 constructable.beginScope();
680 assignable.beginScope();
681 copyable.beginScope();
682 destructable.beginScope();
683 visitStatement( compoundStmt );
684 constructable.endScope();
685 assignable.endScope();
686 copyable.endScope();
687 destructable.endScope();
688 }
689
690 void AutogenerateRoutines::visit( SwitchStmt *switchStmt ) {
691 visitStatement( switchStmt );
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 = safe_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 = safe_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.