source: src/SymTab/Autogen.cc@ 84993ff2

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 84993ff2 was c3acf0aa, checked in by Thierry Delisle <tdelisle@…>, 8 years ago

More header cleaning

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