source: translator/SymTab/Validate.cc @ 4bf5298

ADTaaron-thesisarm-ehast-experimentalcleanup-dtorsctordeferred_resndemanglerenumforall-pointer-decaygc_noraiijacob/cs343-translationjenkins-sandboxmemorynew-astnew-ast-unique-exprnew-envno_listpersistent-indexerpthread-emulationqualifiedEnumresolv-newstringwith_gc
Last change on this file since 4bf5298 was 4bf5298, checked in by Peter A. Buhr <pabuhr@…>, 9 years ago

update merged files from master

  • Property mode set to 100644
File size: 29.6 KB
Line 
1/*
2  The "validate" phase of translation is used to take a syntax tree and convert it into a standard form that aims to be
3  as regular in structure as possible.  Some assumptions can be made regarding the state of the tree after this pass is
4  complete, including:
5
6  - No nested structure or union definitions; any in the input are "hoisted" to the level of the containing struct or
7    union.
8
9  - All enumeration constants have type EnumInstType.
10
11  - The type "void" never occurs in lists of function parameter or return types; neither do tuple types.  A function
12    taking no arguments has no argument types, and tuples are flattened.
13
14  - No context instances exist; they are all replaced by the set of declarations signified by the context, instantiated
15    by the particular set of type arguments.
16
17  - Every declaration is assigned a unique id.
18
19  - No typedef declarations or instances exist; the actual type is substituted for each instance.
20
21  - Each type, struct, and union definition is followed by an appropriate assignment operator.
22
23  - Each use of a struct or union is connected to a complete definition of that struct or union, even if that definition
24    occurs later in the input.
25*/
26
27#include <list>
28#include <iterator>
29#include "Validate.h"
30#include "SynTree/Visitor.h"
31#include "SynTree/Mutator.h"
32#include "SynTree/Type.h"
33#include "SynTree/Statement.h"
34#include "Indexer.h"
35#include "SynTree/TypeSubstitution.h"
36#include "FixFunction.h"
37#include "ImplementationType.h"
38#include "utility.h"
39#include "UniqueName.h"
40#include "AddVisit.h"
41
42
43#define debugPrint( x ) if ( doDebug ) { std::cout << x; }
44
45namespace SymTab {
46    class HoistStruct : public Visitor {
47      public:
48        static void hoistStruct( std::list< Declaration * > &translationUnit );
49 
50        std::list< Declaration * > &get_declsToAdd() { return declsToAdd; }
51 
52        virtual void visit( StructDecl *aggregateDecl );
53        virtual void visit( UnionDecl *aggregateDecl );
54
55        virtual void visit( CompoundStmt *compoundStmt );
56        virtual void visit( IfStmt *ifStmt );
57        virtual void visit( WhileStmt *whileStmt );
58        virtual void visit( ForStmt *forStmt );
59        virtual void visit( SwitchStmt *switchStmt );
60        virtual void visit( ChooseStmt *chooseStmt );
61        virtual void visit( CaseStmt *caseStmt );
62        virtual void visit( CatchStmt *catchStmt );
63      private:
64        HoistStruct();
65
66        template< typename AggDecl > void handleAggregate( AggDecl *aggregateDecl );
67
68        std::list< Declaration * > declsToAdd;
69        bool inStruct;
70    };
71
72    class Pass1 : public Visitor {
73        typedef Visitor Parent;
74        virtual void visit( EnumDecl *aggregateDecl );
75        virtual void visit( FunctionType *func );
76    };
77 
78    class Pass2 : public Indexer {
79        typedef Indexer Parent;
80      public:
81        Pass2( bool doDebug, const Indexer *indexer );
82      private:
83        virtual void visit( StructInstType *structInst );
84        virtual void visit( UnionInstType *unionInst );
85        virtual void visit( ContextInstType *contextInst );
86        virtual void visit( StructDecl *structDecl );
87        virtual void visit( UnionDecl *unionDecl );
88        virtual void visit( TypeInstType *typeInst );
89
90        const Indexer *indexer;
91 
92        typedef std::map< std::string, std::list< StructInstType * > > ForwardStructsType;
93        typedef std::map< std::string, std::list< UnionInstType * > > ForwardUnionsType;
94        ForwardStructsType forwardStructs;
95        ForwardUnionsType forwardUnions;
96    };
97
98    class Pass3 : public Indexer {
99        typedef Indexer Parent;
100      public:
101        Pass3( const Indexer *indexer );
102      private:
103        virtual void visit( ObjectDecl *object );
104        virtual void visit( FunctionDecl *func );
105
106        const Indexer *indexer;
107    };
108
109    class AddStructAssignment : public Visitor {
110      public:
111        static void addStructAssignment( std::list< Declaration * > &translationUnit );
112
113        std::list< Declaration * > &get_declsToAdd() { return declsToAdd; }
114 
115        virtual void visit( StructDecl *structDecl );
116        virtual void visit( UnionDecl *structDecl );
117        virtual void visit( TypeDecl *typeDecl );
118        virtual void visit( ContextDecl *ctxDecl );
119        virtual void visit( FunctionDecl *functionDecl );
120
121        virtual void visit( FunctionType *ftype );
122        virtual void visit( PointerType *ftype );
123 
124        virtual void visit( CompoundStmt *compoundStmt );
125        virtual void visit( IfStmt *ifStmt );
126        virtual void visit( WhileStmt *whileStmt );
127        virtual void visit( ForStmt *forStmt );
128        virtual void visit( SwitchStmt *switchStmt );
129        virtual void visit( ChooseStmt *chooseStmt );
130        virtual void visit( CaseStmt *caseStmt );
131        virtual void visit( CatchStmt *catchStmt );
132
133        AddStructAssignment() : functionNesting( 0 ) {}
134      private:
135        template< typename StmtClass > void visitStatement( StmtClass *stmt );
136 
137        std::list< Declaration * > declsToAdd;
138        std::set< std::string > structsDone;
139        unsigned int functionNesting;                   // current level of nested functions
140    };
141
142    class EliminateTypedef : public Mutator {
143      public:
144        static void eliminateTypedef( std::list< Declaration * > &translationUnit );
145      private:
146        virtual Declaration *mutate( TypedefDecl *typeDecl );
147        virtual TypeDecl *mutate( TypeDecl *typeDecl );
148        virtual DeclarationWithType *mutate( FunctionDecl *funcDecl );
149        virtual ObjectDecl *mutate( ObjectDecl *objDecl );
150        virtual CompoundStmt *mutate( CompoundStmt *compoundStmt );
151        virtual Type *mutate( TypeInstType *aggregateUseType );
152        virtual Expression *mutate( CastExpr *castExpr );
153 
154        std::map< std::string, TypedefDecl * > typedefNames;
155    };
156
157    void validate( std::list< Declaration * > &translationUnit, bool doDebug ) {
158        Pass1 pass1;
159        Pass2 pass2( doDebug, 0 );
160        Pass3 pass3( 0 );
161        EliminateTypedef::eliminateTypedef( translationUnit );
162        HoistStruct::hoistStruct( translationUnit );
163        acceptAll( translationUnit, pass1 );
164        acceptAll( translationUnit, pass2 );
165        AddStructAssignment::addStructAssignment( translationUnit );
166        acceptAll( translationUnit, pass3 );
167    }
168   
169    void validateType( Type *type, const Indexer *indexer ) {
170        Pass1 pass1;
171        Pass2 pass2( false, indexer );
172        Pass3 pass3( indexer );
173        type->accept( pass1 );
174        type->accept( pass2 );
175        type->accept( pass3 );
176    }
177
178    template< typename Visitor >
179    void acceptAndAdd( std::list< Declaration * > &translationUnit, Visitor &visitor, bool addBefore ) {
180        std::list< Declaration * >::iterator i = translationUnit.begin();
181        while ( i != translationUnit.end() ) {
182            (*i)->accept( visitor );
183            std::list< Declaration * >::iterator next = i;
184            next++;
185            if ( ! visitor.get_declsToAdd().empty() ) {
186                translationUnit.splice( addBefore ? i : next, visitor.get_declsToAdd() );
187            } // if
188            i = next;
189        } // while
190    }
191
192    void HoistStruct::hoistStruct( std::list< Declaration * > &translationUnit ) {
193        HoistStruct hoister;
194        acceptAndAdd( translationUnit, hoister, true );
195    }
196
197    HoistStruct::HoistStruct() : inStruct( false ) {
198    }
199
200    void filter( std::list< Declaration * > &declList, bool (*pred)( Declaration * ), bool doDelete ) {
201        std::list< Declaration * >::iterator i = declList.begin();
202        while ( i != declList.end() ) {
203            std::list< Declaration * >::iterator next = i;
204            ++next;
205            if ( pred( *i ) ) {
206                if ( doDelete ) {
207                    delete *i;
208                } // if
209                declList.erase( i );
210            } // if
211            i = next;
212        } // while
213    }
214
215    bool isStructOrUnion( Declaration *decl ) {
216        return dynamic_cast< StructDecl * >( decl ) || dynamic_cast< UnionDecl * >( decl );
217    }
218
219    template< typename AggDecl >
220    void HoistStruct::handleAggregate( AggDecl *aggregateDecl ) {
221        if ( inStruct ) {
222            // Add elements in stack order corresponding to nesting structure.
223            declsToAdd.push_front( aggregateDecl );
224            Visitor::visit( aggregateDecl );
225        } else {
226            inStruct = true;
227            Visitor::visit( aggregateDecl );
228            inStruct = false;
229        } // if
230        // Always remove the hoisted aggregate from the inner structure.
231        filter( aggregateDecl->get_members(), isStructOrUnion, false );
232    }
233
234    void HoistStruct::visit( StructDecl *aggregateDecl ) {
235        handleAggregate( aggregateDecl );
236    }
237
238    void HoistStruct::visit( UnionDecl *aggregateDecl ) {
239        handleAggregate( aggregateDecl );
240    }
241
242    void HoistStruct::visit( CompoundStmt *compoundStmt ) {
243        addVisit( compoundStmt, *this );
244    }
245
246    void HoistStruct::visit( IfStmt *ifStmt ) {
247        addVisit( ifStmt, *this );
248    }
249
250    void HoistStruct::visit( WhileStmt *whileStmt ) {
251        addVisit( whileStmt, *this );
252    }
253
254    void HoistStruct::visit( ForStmt *forStmt ) {
255        addVisit( forStmt, *this );
256    }
257
258    void HoistStruct::visit( SwitchStmt *switchStmt ) {
259        addVisit( switchStmt, *this );
260    }
261
262    void HoistStruct::visit( ChooseStmt *switchStmt ) {
263        addVisit( switchStmt, *this );
264    }
265
266    void HoistStruct::visit( CaseStmt *caseStmt ) {
267        addVisit( caseStmt, *this );
268    }
269
270    void HoistStruct::visit( CatchStmt *cathStmt ) {
271        addVisit( cathStmt, *this );
272    }
273
274    void Pass1::visit( EnumDecl *enumDecl ) {
275        // Set the type of each member of the enumeration to be EnumConstant
276 
277        for ( std::list< Declaration * >::iterator i = enumDecl->get_members().begin(); i != enumDecl->get_members().end(); ++i ) {
278            ObjectDecl *obj = dynamic_cast< ObjectDecl * >( *i );
279            assert( obj );
280            obj->set_type( new EnumInstType( Type::Qualifiers( true, false, false, false, false, false ), enumDecl->get_name() ) );
281        } // for
282        Parent::visit( enumDecl );
283    }
284
285    namespace {
286        template< typename DWTIterator >
287        void fixFunctionList( DWTIterator begin, DWTIterator end, FunctionType *func ) {
288            // the only case in which "void" is valid is where it is the only one in the list; then
289            // it should be removed entirely
290            // other fix ups are handled by the FixFunction class
291            if ( begin == end ) return;
292            FixFunction fixer;
293            DWTIterator i = begin;
294            *i = (*i )->acceptMutator( fixer );
295            if ( fixer.get_isVoid() ) {
296                DWTIterator j = i;
297                ++i;
298                func->get_parameters().erase( j );
299                if ( i != end ) { 
300                    throw SemanticError( "invalid type void in function type ", func );
301                } // if
302            } else {
303                ++i;
304                for ( ; i != end; ++i ) {
305                    FixFunction fixer;
306                    *i = (*i )->acceptMutator( fixer );
307                    if ( fixer.get_isVoid() ) {
308                        throw SemanticError( "invalid type void in function type ", func );
309                    } // if
310                } // for
311            } // if
312        }
313    }
314
315    void Pass1::visit( FunctionType *func ) {
316        // Fix up parameters and return types
317        fixFunctionList( func->get_parameters().begin(), func->get_parameters().end(), func );
318        fixFunctionList( func->get_returnVals().begin(), func->get_returnVals().end(), func );
319        Visitor::visit( func );
320    }
321
322    Pass2::Pass2( bool doDebug, const Indexer *other_indexer ) : Indexer( doDebug ) {
323        if ( other_indexer ) {
324            indexer = other_indexer;
325        } else {
326            indexer = this;
327        } // if
328    }
329
330    void Pass2::visit( StructInstType *structInst ) {
331        Parent::visit( structInst );
332        StructDecl *st = indexer->lookupStruct( structInst->get_name() );
333        // it's not a semantic error if the struct is not found, just an implicit forward declaration
334        if ( st ) {
335            assert( ! structInst->get_baseStruct() || structInst->get_baseStruct()->get_members().empty() || ! st->get_members().empty() );
336            structInst->set_baseStruct( st );
337        } // if
338        if ( ! st || st->get_members().empty() ) {
339            // use of forward declaration
340            forwardStructs[ structInst->get_name() ].push_back( structInst );
341        } // if
342    }
343
344    void Pass2::visit( UnionInstType *unionInst ) {
345        Parent::visit( unionInst );
346        UnionDecl *un = indexer->lookupUnion( unionInst->get_name() );
347        // it's not a semantic error if the union is not found, just an implicit forward declaration
348        if ( un ) {
349            unionInst->set_baseUnion( un );
350        } // if
351        if ( ! un || un->get_members().empty() ) {
352            // use of forward declaration
353            forwardUnions[ unionInst->get_name() ].push_back( unionInst );
354        } // if
355    }
356
357    void Pass2::visit( ContextInstType *contextInst ) {
358        Parent::visit( contextInst );
359        ContextDecl *ctx = indexer->lookupContext( contextInst->get_name() );
360        if ( ! ctx ) {
361            throw SemanticError( "use of undeclared context " + contextInst->get_name() );
362        } // if
363        for ( std::list< TypeDecl * >::const_iterator i = ctx->get_parameters().begin(); i != ctx->get_parameters().end(); ++i ) {
364            for ( std::list< DeclarationWithType * >::const_iterator assert = (*i )->get_assertions().begin(); assert != (*i )->get_assertions().end(); ++assert ) {
365                if ( ContextInstType *otherCtx = dynamic_cast< ContextInstType * >(*assert ) ) {
366                    cloneAll( otherCtx->get_members(), contextInst->get_members() );
367                } else {
368                    contextInst->get_members().push_back( (*assert )->clone() );
369                } // if
370            } // for
371        } // for
372        applySubstitution( ctx->get_parameters().begin(), ctx->get_parameters().end(), contextInst->get_parameters().begin(), ctx->get_members().begin(), ctx->get_members().end(), back_inserter( contextInst->get_members() ) );
373    }
374
375    void Pass2::visit( StructDecl *structDecl ) {
376        if ( ! structDecl->get_members().empty() ) {
377            ForwardStructsType::iterator fwds = forwardStructs.find( structDecl->get_name() );
378            if ( fwds != forwardStructs.end() ) {
379                for ( std::list< StructInstType * >::iterator inst = fwds->second.begin(); inst != fwds->second.end(); ++inst ) {
380                    (*inst )->set_baseStruct( structDecl );
381                } // for
382                forwardStructs.erase( fwds );
383            } // if
384        } // if
385        Indexer::visit( structDecl );
386    }
387
388    void Pass2::visit( UnionDecl *unionDecl ) {
389        if ( ! unionDecl->get_members().empty() ) {
390            ForwardUnionsType::iterator fwds = forwardUnions.find( unionDecl->get_name() );
391            if ( fwds != forwardUnions.end() ) {
392                for ( std::list< UnionInstType * >::iterator inst = fwds->second.begin(); inst != fwds->second.end(); ++inst ) {
393                    (*inst )->set_baseUnion( unionDecl );
394                } // for
395                forwardUnions.erase( fwds );
396            } // if
397        } // if
398        Indexer::visit( unionDecl );
399    }
400
401    void Pass2::visit( TypeInstType *typeInst ) {
402        if ( NamedTypeDecl *namedTypeDecl = lookupType( typeInst->get_name() ) ) {
403            if ( TypeDecl *typeDecl = dynamic_cast< TypeDecl * >( namedTypeDecl ) ) {
404                typeInst->set_isFtype( typeDecl->get_kind() == TypeDecl::Ftype );
405            } // if
406        } // if
407    }
408
409    Pass3::Pass3( const Indexer *other_indexer ) :  Indexer( false ) {
410        if ( other_indexer ) {
411            indexer = other_indexer;
412        } else {
413            indexer = this;
414        } // if
415    }
416
417    void forallFixer( Type *func ) {
418        // Fix up assertions
419        for ( std::list< TypeDecl * >::iterator type = func->get_forall().begin(); type != func->get_forall().end(); ++type ) {
420            std::list< DeclarationWithType * > toBeDone, nextRound;
421            toBeDone.splice( toBeDone.end(), (*type )->get_assertions() );
422            while ( ! toBeDone.empty() ) {
423                for ( std::list< DeclarationWithType * >::iterator assertion = toBeDone.begin(); assertion != toBeDone.end(); ++assertion ) {
424                    if ( ContextInstType *ctx = dynamic_cast< ContextInstType * >( (*assertion )->get_type() ) ) {
425                        for ( std::list< Declaration * >::const_iterator i = ctx->get_members().begin(); i != ctx->get_members().end(); ++i ) {
426                            DeclarationWithType *dwt = dynamic_cast< DeclarationWithType * >( *i );
427                            assert( dwt );
428                            nextRound.push_back( dwt->clone() );
429                        }
430                        delete ctx;
431                    } else {
432                        FixFunction fixer;
433                        *assertion = (*assertion )->acceptMutator( fixer );
434                        if ( fixer.get_isVoid() ) {
435                            throw SemanticError( "invalid type void in assertion of function ", func );
436                        }
437                        (*type )->get_assertions().push_back( *assertion );
438                    }
439                }
440                toBeDone.clear();
441                toBeDone.splice( toBeDone.end(), nextRound );
442            }
443        }
444    }
445
446    void Pass3::visit( ObjectDecl *object ) {
447        forallFixer( object->get_type() );
448        if ( PointerType *pointer = dynamic_cast< PointerType * >( object->get_type() ) ) {
449            forallFixer( pointer->get_base() );
450        } // if
451        Parent::visit( object );
452        object->fixUniqueId();
453    }
454
455    void Pass3::visit( FunctionDecl *func ) {
456        forallFixer( func->get_type() );
457        Parent::visit( func );
458        func->fixUniqueId();
459    }
460
461    static const std::list< std::string > noLabels;
462
463    void AddStructAssignment::addStructAssignment( std::list< Declaration * > &translationUnit ) {
464        AddStructAssignment visitor;
465        acceptAndAdd( translationUnit, visitor, false );
466    }
467
468    template< typename OutputIterator >
469    void makeScalarAssignment( ObjectDecl *srcParam, ObjectDecl *dstParam, DeclarationWithType *member, OutputIterator out ) {
470        ObjectDecl *obj = dynamic_cast<ObjectDecl *>( member );
471        // unnamed bit fields are not copied as they cannot be accessed
472        if ( obj != NULL && obj->get_name() == "" && obj->get_bitfieldWidth() != NULL ) return;
473
474        UntypedExpr *assignExpr = new UntypedExpr( new NameExpr( "?=?" ) );
475 
476        UntypedExpr *derefExpr = new UntypedExpr( new NameExpr( "*?" ) );
477        derefExpr->get_args().push_back( new VariableExpr( dstParam ) );
478 
479        // do something special for unnamed members
480        Expression *dstselect = new AddressExpr( new MemberExpr( member, derefExpr ) );
481        assignExpr->get_args().push_back( dstselect );
482 
483        Expression *srcselect = new MemberExpr( member, new VariableExpr( srcParam ) );
484        assignExpr->get_args().push_back( srcselect );
485 
486        *out++ = new ExprStmt( noLabels, assignExpr );
487    }
488
489    template< typename OutputIterator >
490    void makeArrayAssignment( ObjectDecl *srcParam, ObjectDecl *dstParam, DeclarationWithType *member, ArrayType *array, OutputIterator out ) {
491        static UniqueName indexName( "_index" );
492 
493        // for a flexible array member nothing is done -- user must define own assignment
494        if ( ! array->get_dimension() ) return;
495 
496        ObjectDecl *index = new ObjectDecl( indexName.newName(), Declaration::NoStorageClass, LinkageSpec::C, 0, new BasicType( Type::Qualifiers(), BasicType::SignedInt ), 0 );
497        *out++ = new DeclStmt( noLabels, index );
498 
499        UntypedExpr *init = new UntypedExpr( new NameExpr( "?=?" ) );
500        init->get_args().push_back( new AddressExpr( new VariableExpr( index ) ) );
501        init->get_args().push_back( new NameExpr( "0" ) );
502        Statement *initStmt = new ExprStmt( noLabels, init );
503 
504        UntypedExpr *cond = new UntypedExpr( new NameExpr( "?<?" ) );
505        cond->get_args().push_back( new VariableExpr( index ) );
506        cond->get_args().push_back( array->get_dimension()->clone() );
507 
508        UntypedExpr *inc = new UntypedExpr( new NameExpr( "++?" ) );
509        inc->get_args().push_back( new AddressExpr( new VariableExpr( index ) ) );
510 
511        UntypedExpr *assignExpr = new UntypedExpr( new NameExpr( "?=?" ) );
512 
513        UntypedExpr *derefExpr = new UntypedExpr( new NameExpr( "*?" ) );
514        derefExpr->get_args().push_back( new VariableExpr( dstParam ) );
515 
516        Expression *dstselect = new MemberExpr( member, derefExpr );
517        UntypedExpr *dstIndex = new UntypedExpr( new NameExpr( "?+?" ) );
518        dstIndex->get_args().push_back( dstselect );
519        dstIndex->get_args().push_back( new VariableExpr( index ) );
520        assignExpr->get_args().push_back( dstIndex );
521 
522        Expression *srcselect = new MemberExpr( member, new VariableExpr( srcParam ) );
523        UntypedExpr *srcIndex = new UntypedExpr( new NameExpr( "?[?]" ) );
524        srcIndex->get_args().push_back( srcselect );
525        srcIndex->get_args().push_back( new VariableExpr( index ) );
526        assignExpr->get_args().push_back( srcIndex );
527 
528        *out++ = new ForStmt( noLabels, initStmt, cond, inc, new ExprStmt( noLabels, assignExpr ) );
529    }
530
531    Declaration *makeStructAssignment( StructDecl *aggregateDecl, StructInstType *refType, unsigned int functionNesting ) {
532        FunctionType *assignType = new FunctionType( Type::Qualifiers(), false );
533 
534        ObjectDecl *returnVal = new ObjectDecl( "", Declaration::NoStorageClass, LinkageSpec::Cforall, 0, refType->clone(), 0 );
535        assignType->get_returnVals().push_back( returnVal );
536 
537        ObjectDecl *dstParam = new ObjectDecl( "_dst", Declaration::NoStorageClass, LinkageSpec::Cforall, 0, new PointerType( Type::Qualifiers(), refType->clone() ), 0 );
538        assignType->get_parameters().push_back( dstParam );
539 
540        ObjectDecl *srcParam = new ObjectDecl( "_src", Declaration::NoStorageClass, LinkageSpec::Cforall, 0, refType, 0 );
541        assignType->get_parameters().push_back( srcParam );
542
543        // Routines at global scope marked "static" to prevent multiple definitions is separate translation units
544        // because each unit generates copies of the default routines for each aggregate.
545        FunctionDecl *assignDecl = new FunctionDecl( "?=?", functionNesting > 0 ? Declaration::NoStorageClass : Declaration::Static, LinkageSpec::AutoGen, assignType, new CompoundStmt( noLabels ), true );
546        assignDecl->fixUniqueId();
547 
548        for ( std::list< Declaration * >::const_iterator member = aggregateDecl->get_members().begin(); member != aggregateDecl->get_members().end(); ++member ) {
549            if ( DeclarationWithType *dwt = dynamic_cast< DeclarationWithType * >( *member ) ) {
550                if ( ArrayType *array = dynamic_cast< ArrayType * >( dwt->get_type() ) ) {
551                    makeArrayAssignment( srcParam, dstParam, dwt, array, back_inserter( assignDecl->get_statements()->get_kids() ) );
552                } else {
553                    makeScalarAssignment( srcParam, dstParam, dwt, back_inserter( assignDecl->get_statements()->get_kids() ) );
554                } // if
555            } // if
556        } // for
557        assignDecl->get_statements()->get_kids().push_back( new ReturnStmt( noLabels, new VariableExpr( srcParam ) ) );
558 
559        return assignDecl;
560    }
561
562    Declaration *makeUnionAssignment( UnionDecl *aggregateDecl, UnionInstType *refType, unsigned int functionNesting ) {
563        FunctionType *assignType = new FunctionType( Type::Qualifiers(), false );
564 
565        ObjectDecl *returnVal = new ObjectDecl( "", Declaration::NoStorageClass, LinkageSpec::Cforall, 0, refType->clone(), 0 );
566        assignType->get_returnVals().push_back( returnVal );
567 
568        ObjectDecl *dstParam = new ObjectDecl( "_dst", Declaration::NoStorageClass, LinkageSpec::Cforall, 0, new PointerType( Type::Qualifiers(), refType->clone() ), 0 );
569        assignType->get_parameters().push_back( dstParam );
570 
571        ObjectDecl *srcParam = new ObjectDecl( "_src", Declaration::NoStorageClass, LinkageSpec::Cforall, 0, refType, 0 );
572        assignType->get_parameters().push_back( srcParam );
573 
574        // Routines at global scope marked "static" to prevent multiple definitions is separate translation units
575        // because each unit generates copies of the default routines for each aggregate.
576        FunctionDecl *assignDecl = new FunctionDecl( "?=?",  functionNesting > 0 ? Declaration::NoStorageClass : Declaration::Static, LinkageSpec::AutoGen, assignType, new CompoundStmt( noLabels ), true );
577        assignDecl->fixUniqueId();
578 
579        UntypedExpr *copy = new UntypedExpr( new NameExpr( "__builtin_memcpy" ) );
580        copy->get_args().push_back( new VariableExpr( dstParam ) );
581        copy->get_args().push_back( new AddressExpr( new VariableExpr( srcParam ) ) );
582        copy->get_args().push_back( new SizeofExpr( refType->clone() ) );
583
584        assignDecl->get_statements()->get_kids().push_back( new ExprStmt( noLabels, copy ) );
585        assignDecl->get_statements()->get_kids().push_back( new ReturnStmt( noLabels, new VariableExpr( srcParam ) ) );
586 
587        return assignDecl;
588    }
589
590    void AddStructAssignment::visit( StructDecl *structDecl ) {
591        if ( ! structDecl->get_members().empty() && structsDone.find( structDecl->get_name() ) == structsDone.end() ) {
592            StructInstType *structInst = new StructInstType( Type::Qualifiers(), structDecl->get_name() );
593            structInst->set_baseStruct( structDecl );
594            declsToAdd.push_back( makeStructAssignment( structDecl, structInst, functionNesting ) );
595            structsDone.insert( structDecl->get_name() );
596        } // if
597    }
598
599    void AddStructAssignment::visit( UnionDecl *unionDecl ) {
600        if ( ! unionDecl->get_members().empty() ) {
601            UnionInstType *unionInst = new UnionInstType( Type::Qualifiers(), unionDecl->get_name() );
602            unionInst->set_baseUnion( unionDecl );
603            declsToAdd.push_back( makeUnionAssignment( unionDecl, unionInst, functionNesting ) );
604        } // if
605    }
606
607    void AddStructAssignment::visit( TypeDecl *typeDecl ) {
608        CompoundStmt *stmts = 0;
609        TypeInstType *typeInst = new TypeInstType( Type::Qualifiers(), typeDecl->get_name(), false );
610        typeInst->set_baseType( typeDecl );
611        ObjectDecl *src = new ObjectDecl( "_src", Declaration::NoStorageClass, LinkageSpec::Cforall, 0, typeInst->clone(), 0 );
612        ObjectDecl *dst = new ObjectDecl( "_dst", Declaration::NoStorageClass, LinkageSpec::Cforall, 0, new PointerType( Type::Qualifiers(), typeInst->clone() ), 0 );
613        if ( typeDecl->get_base() ) {
614            stmts = new CompoundStmt( std::list< Label >() );
615            UntypedExpr *assign = new UntypedExpr( new NameExpr( "?=?" ) );
616            assign->get_args().push_back( new CastExpr( new VariableExpr( dst ), new PointerType( Type::Qualifiers(), typeDecl->get_base()->clone() ) ) );
617            assign->get_args().push_back( new CastExpr( new VariableExpr( src ), typeDecl->get_base()->clone() ) );
618            stmts->get_kids().push_back( new ReturnStmt( std::list< Label >(), assign ) );
619        } // if
620        FunctionType *type = new FunctionType( Type::Qualifiers(), false );
621        type->get_returnVals().push_back( new ObjectDecl( "", Declaration::NoStorageClass, LinkageSpec::Cforall, 0, typeInst, 0 ) );
622        type->get_parameters().push_back( dst );
623        type->get_parameters().push_back( src );
624        FunctionDecl *func = new FunctionDecl( "?=?", Declaration::NoStorageClass, LinkageSpec::AutoGen, type, stmts, false );
625        declsToAdd.push_back( func );
626    }
627
628    void addDecls( std::list< Declaration * > &declsToAdd, std::list< Statement * > &statements, std::list< Statement * >::iterator i ) {
629        if ( ! declsToAdd.empty() ) {
630            for ( std::list< Declaration * >::iterator decl = declsToAdd.begin(); decl != declsToAdd.end(); ++decl ) {
631                statements.insert( i, new DeclStmt( noLabels, *decl ) );
632            } // for
633            declsToAdd.clear();
634        } // if
635    }
636
637    void AddStructAssignment::visit( FunctionType *) {
638        // ensure that we don't add assignment ops for types defined as part of the function
639    }
640
641    void AddStructAssignment::visit( PointerType *) {
642        // ensure that we don't add assignment ops for types defined as part of the pointer
643    }
644
645    void AddStructAssignment::visit( ContextDecl *) {
646        // ensure that we don't add assignment ops for types defined as part of the context
647    }
648
649    template< typename StmtClass >
650    inline void AddStructAssignment::visitStatement( StmtClass *stmt ) {
651        std::set< std::string > oldStructs = structsDone;
652        addVisit( stmt, *this );
653        structsDone = oldStructs;
654    }
655
656    void AddStructAssignment::visit( FunctionDecl *functionDecl ) {
657        maybeAccept( functionDecl->get_functionType(), *this );
658        acceptAll( functionDecl->get_oldDecls(), *this );
659        functionNesting += 1;
660        maybeAccept( functionDecl->get_statements(), *this );
661        functionNesting -= 1;
662    }
663
664    void AddStructAssignment::visit( CompoundStmt *compoundStmt ) {
665        visitStatement( compoundStmt );
666    }
667
668    void AddStructAssignment::visit( IfStmt *ifStmt ) {
669        visitStatement( ifStmt );
670    }
671
672    void AddStructAssignment::visit( WhileStmt *whileStmt ) {
673        visitStatement( whileStmt );
674    }
675
676    void AddStructAssignment::visit( ForStmt *forStmt ) {
677        visitStatement( forStmt );
678    }
679
680    void AddStructAssignment::visit( SwitchStmt *switchStmt ) {
681        visitStatement( switchStmt );
682    }
683
684    void AddStructAssignment::visit( ChooseStmt *switchStmt ) {
685        visitStatement( switchStmt );
686    }
687
688    void AddStructAssignment::visit( CaseStmt *caseStmt ) {
689        visitStatement( caseStmt );
690    }
691
692    void AddStructAssignment::visit( CatchStmt *cathStmt ) {
693        visitStatement( cathStmt );
694    }
695
696    bool isTypedef( Declaration *decl ) {
697        return dynamic_cast< TypedefDecl * >( decl );
698    }
699
700    void EliminateTypedef::eliminateTypedef( std::list< Declaration * > &translationUnit ) {
701        EliminateTypedef eliminator;
702        mutateAll( translationUnit, eliminator );
703        filter( translationUnit, isTypedef, true );
704    }
705
706    Type *EliminateTypedef::mutate( TypeInstType *typeInst ) {
707        std::map< std::string, TypedefDecl * >::const_iterator def = typedefNames.find( typeInst->get_name() );
708        if ( def != typedefNames.end() ) {
709            Type *ret = def->second->get_base()->clone();
710            ret->get_qualifiers() += typeInst->get_qualifiers();
711            delete typeInst;
712            return ret;
713        } // if
714        return typeInst;
715    }
716
717    Declaration *EliminateTypedef::mutate( TypedefDecl *tyDecl ) {
718        Declaration *ret = Mutator::mutate( tyDecl );
719        typedefNames[ tyDecl->get_name() ] = tyDecl;
720        // When a typedef is a forward declaration:
721        //    typedef struct screen SCREEN;
722        // the declaration portion must be retained:
723        //    struct screen;
724        // because the expansion of the typedef is:
725        //    void rtn( SCREEN *p ) => void rtn( struct screen *p )
726        // hence the type-name "screen" must be defined.
727        // Note, qualifiers on the typedef are superfluous for the forward declaration.
728        if ( StructInstType *aggDecl = dynamic_cast< StructInstType * >( tyDecl->get_base() ) ) {
729            return new StructDecl( aggDecl->get_name() );
730        } else if ( UnionInstType *aggDecl = dynamic_cast< UnionInstType * >( tyDecl->get_base() ) ) {
731            return new UnionDecl( aggDecl->get_name() );
732        } else {
733            return ret;
734        } // if
735    }
736
737    TypeDecl *EliminateTypedef::mutate( TypeDecl *typeDecl ) {
738        std::map< std::string, TypedefDecl * >::iterator i = typedefNames.find( typeDecl->get_name() );
739        if ( i != typedefNames.end() ) {
740            typedefNames.erase( i ) ;
741        } // if
742        return typeDecl;
743    }
744
745    DeclarationWithType *EliminateTypedef::mutate( FunctionDecl *funcDecl ) {
746        std::map< std::string, TypedefDecl * > oldNames = typedefNames;
747        DeclarationWithType *ret = Mutator::mutate( funcDecl );
748        typedefNames = oldNames;
749        return ret;
750    }
751
752    ObjectDecl *EliminateTypedef::mutate( ObjectDecl *objDecl ) {
753        std::map< std::string, TypedefDecl * > oldNames = typedefNames;
754        ObjectDecl *ret = Mutator::mutate( objDecl );
755        typedefNames = oldNames;
756        return ret;
757    }
758
759    Expression *EliminateTypedef::mutate( CastExpr *castExpr ) {
760        std::map< std::string, TypedefDecl * > oldNames = typedefNames;
761        Expression *ret = Mutator::mutate( castExpr );
762        typedefNames = oldNames;
763        return ret;
764    }
765
766    CompoundStmt *EliminateTypedef::mutate( CompoundStmt *compoundStmt ) {
767        std::map< std::string, TypedefDecl * > oldNames = typedefNames;
768        CompoundStmt *ret = Mutator::mutate( compoundStmt );
769        std::list< Statement * >::iterator i = compoundStmt->get_kids().begin();
770        while ( i != compoundStmt->get_kids().end() ) {
771            std::list< Statement * >::iterator next = i;
772            ++next;
773            if ( DeclStmt *declStmt = dynamic_cast< DeclStmt * >( *i ) ) {
774                if ( dynamic_cast< TypedefDecl * >( declStmt->get_decl() ) ) {
775                    delete *i;
776                    compoundStmt->get_kids().erase( i );
777                } // if
778            } // if
779            i = next;
780        } // while
781        typedefNames = oldNames;
782        return ret;
783    }
784} // namespace SymTab
Note: See TracBrowser for help on using the repository browser.