source: src/SymTab/Validate.cc @ 679864e1

ADTaaron-thesisarm-ehcleanup-dtorsctordeferred_resndemanglerenumforall-pointer-decayjacob/cs343-translationjenkins-sandboxnew-astnew-ast-unique-exprnew-envno_listpersistent-indexerpthread-emulationqualifiedEnumresolv-newwith_gc
Last change on this file since 679864e1 was 679864e1, checked in by Rob Schluntz <rschlunt@…>, 8 years ago

link typedecl to its implementation type, typedecl initialization hack in resolver

  • 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// Validate.cc --
8//
9// Author           : Richard C. Bilson
10// Created On       : Sun May 17 21:50:04 2015
11// Last Modified By : Rob Schluntz
12// Last Modified On : Tue Oct 06 15:40:35 2015
13// Update Count     : 219
14//
15
16// The "validate" phase of translation is used to take a syntax tree and convert it into a standard form that aims to be
17// as regular in structure as possible.  Some assumptions can be made regarding the state of the tree after this pass is
18// complete, including:
19//
20// - No nested structure or union definitions; any in the input are "hoisted" to the level of the containing struct or
21//   union.
22//
23// - All enumeration constants have type EnumInstType.
24//
25// - The type "void" never occurs in lists of function parameter or return types; neither do tuple types.  A function
26//   taking no arguments has no argument types, and tuples are flattened.
27//
28// - No context instances exist; they are all replaced by the set of declarations signified by the context, instantiated
29//   by the particular set of type arguments.
30//
31// - Every declaration is assigned a unique id.
32//
33// - No typedef declarations or instances exist; the actual type is substituted for each instance.
34//
35// - Each type, struct, and union definition is followed by an appropriate assignment operator.
36//
37// - Each use of a struct or union is connected to a complete definition of that struct or union, even if that
38//   definition occurs later in the input.
39
40#include <list>
41#include <iterator>
42#include "Validate.h"
43#include "SynTree/Visitor.h"
44#include "SynTree/Mutator.h"
45#include "SynTree/Type.h"
46#include "SynTree/Statement.h"
47#include "SynTree/TypeSubstitution.h"
48#include "Indexer.h"
49#include "FixFunction.h"
50// #include "ImplementationType.h"
51#include "utility.h"
52#include "UniqueName.h"
53#include "AddVisit.h"
54#include "MakeLibCfa.h"
55#include "TypeEquality.h"
56
57#define debugPrint( x ) if ( doDebug ) { std::cout << x; }
58
59namespace SymTab {
60        class HoistStruct : public Visitor {
61          public:
62                /// Flattens nested struct types
63                static void hoistStruct( std::list< Declaration * > &translationUnit );
64 
65                std::list< Declaration * > &get_declsToAdd() { return declsToAdd; }
66 
67                virtual void visit( StructDecl *aggregateDecl );
68                virtual void visit( UnionDecl *aggregateDecl );
69
70                virtual void visit( CompoundStmt *compoundStmt );
71                virtual void visit( IfStmt *ifStmt );
72                virtual void visit( WhileStmt *whileStmt );
73                virtual void visit( ForStmt *forStmt );
74                virtual void visit( SwitchStmt *switchStmt );
75                virtual void visit( ChooseStmt *chooseStmt );
76                virtual void visit( CaseStmt *caseStmt );
77                virtual void visit( CatchStmt *catchStmt );
78          private:
79                HoistStruct();
80
81                template< typename AggDecl > void handleAggregate( AggDecl *aggregateDecl );
82
83                std::list< Declaration * > declsToAdd;
84                bool inStruct;
85        };
86
87        /// Replaces enum types by int, and function or array types in function parameter and return lists by appropriate pointers
88        class Pass1 : public Visitor {
89                typedef Visitor Parent;
90                virtual void visit( EnumDecl *aggregateDecl );
91                virtual void visit( FunctionType *func );
92        };
93
94        /// Associates forward declarations of aggregates with their definitions
95        class Pass2 : public Indexer {
96                typedef Indexer Parent;
97          public:
98                Pass2( bool doDebug, const Indexer *indexer );
99          private:
100                virtual void visit( StructInstType *structInst );
101                virtual void visit( UnionInstType *unionInst );
102                virtual void visit( ContextInstType *contextInst );
103                virtual void visit( StructDecl *structDecl );
104                virtual void visit( UnionDecl *unionDecl );
105                virtual void visit( TypeInstType *typeInst );
106
107                const Indexer *indexer;
108 
109                typedef std::map< std::string, std::list< StructInstType * > > ForwardStructsType;
110                typedef std::map< std::string, std::list< UnionInstType * > > ForwardUnionsType;
111                ForwardStructsType forwardStructs;
112                ForwardUnionsType forwardUnions;
113        };
114
115        /// Replaces array and function types in forall lists by appropriate pointer type
116        class Pass3 : public Indexer {
117                typedef Indexer Parent;
118          public:
119                Pass3( const Indexer *indexer );
120          private:
121                virtual void visit( ObjectDecl *object );
122                virtual void visit( FunctionDecl *func );
123
124                const Indexer *indexer;
125        };
126
127        class AddStructAssignment : public Visitor {
128          public:
129                /// Generates assignment operators for aggregate types as required
130                static void addStructAssignment( std::list< Declaration * > &translationUnit );
131
132                std::list< Declaration * > &get_declsToAdd() { return declsToAdd; }
133 
134                virtual void visit( EnumDecl *enumDecl );
135                virtual void visit( StructDecl *structDecl );
136                virtual void visit( UnionDecl *structDecl );
137                virtual void visit( TypeDecl *typeDecl );
138                virtual void visit( ContextDecl *ctxDecl );
139                virtual void visit( FunctionDecl *functionDecl );
140
141                virtual void visit( FunctionType *ftype );
142                virtual void visit( PointerType *ftype );
143 
144                virtual void visit( CompoundStmt *compoundStmt );
145                virtual void visit( IfStmt *ifStmt );
146                virtual void visit( WhileStmt *whileStmt );
147                virtual void visit( ForStmt *forStmt );
148                virtual void visit( SwitchStmt *switchStmt );
149                virtual void visit( ChooseStmt *chooseStmt );
150                virtual void visit( CaseStmt *caseStmt );
151                virtual void visit( CatchStmt *catchStmt );
152
153                AddStructAssignment() : functionNesting( 0 ) {}
154          private:
155                template< typename StmtClass > void visitStatement( StmtClass *stmt );
156 
157                std::list< Declaration * > declsToAdd;
158                std::set< std::string > structsDone;
159                unsigned int functionNesting;                   // current level of nested functions
160        };
161
162        class EliminateTypedef : public Mutator {
163          public:
164          EliminateTypedef() : scopeLevel( 0 ) {}
165            /// Replaces typedefs by forward declarations
166                static void eliminateTypedef( std::list< Declaration * > &translationUnit );
167          private:
168                virtual Declaration *mutate( TypedefDecl *typeDecl );
169                virtual TypeDecl *mutate( TypeDecl *typeDecl );
170                virtual DeclarationWithType *mutate( FunctionDecl *funcDecl );
171                virtual DeclarationWithType *mutate( ObjectDecl *objDecl );
172                virtual CompoundStmt *mutate( CompoundStmt *compoundStmt );
173                virtual Type *mutate( TypeInstType *aggregateUseType );
174                virtual Expression *mutate( CastExpr *castExpr );
175
176                virtual Declaration *mutate( StructDecl * structDecl );
177                virtual Declaration *mutate( UnionDecl * unionDecl );
178                virtual Declaration *mutate( EnumDecl * enumDecl );
179                virtual Declaration *mutate( ContextDecl * contextDecl );
180
181                template<typename AggDecl>
182                AggDecl *handleAggregate( AggDecl * aggDecl );
183
184                typedef std::map< std::string, std::pair< TypedefDecl *, int > > TypedefMap;
185                typedef std::map< std::string, TypeDecl * > TypeDeclMap;
186                TypedefMap typedefNames;
187                TypeDeclMap typedeclNames;
188                int scopeLevel;
189        };
190
191        void validate( std::list< Declaration * > &translationUnit, bool doDebug ) {
192                Pass1 pass1;
193                Pass2 pass2( doDebug, 0 );
194                Pass3 pass3( 0 );
195                EliminateTypedef::eliminateTypedef( translationUnit );
196                HoistStruct::hoistStruct( translationUnit );
197                acceptAll( translationUnit, pass1 );
198                acceptAll( translationUnit, pass2 );
199                // need to collect all of the assignment operators prior to
200                // this point and only generate assignment operators if one doesn't exist
201                AddStructAssignment::addStructAssignment( translationUnit );
202                acceptAll( translationUnit, pass3 );
203        }
204       
205        void validateType( Type *type, const Indexer *indexer ) {
206                Pass1 pass1;
207                Pass2 pass2( false, indexer );
208                Pass3 pass3( indexer );
209                type->accept( pass1 );
210                type->accept( pass2 );
211                type->accept( pass3 );
212        }
213
214        template< typename Visitor >
215        void acceptAndAdd( std::list< Declaration * > &translationUnit, Visitor &visitor, bool addBefore ) {
216                std::list< Declaration * >::iterator i = translationUnit.begin();
217                while ( i != translationUnit.end() ) {
218                        (*i)->accept( visitor );
219                        std::list< Declaration * >::iterator next = i;
220                        next++;
221                        if ( ! visitor.get_declsToAdd().empty() ) {
222                                translationUnit.splice( addBefore ? i : next, visitor.get_declsToAdd() );
223                        } // if
224                        i = next;
225                } // while
226        }
227
228        void HoistStruct::hoistStruct( std::list< Declaration * > &translationUnit ) {
229                HoistStruct hoister;
230                acceptAndAdd( translationUnit, hoister, true );
231        }
232
233        HoistStruct::HoistStruct() : inStruct( false ) {
234        }
235
236        void filter( std::list< Declaration * > &declList, bool (*pred)( Declaration * ), bool doDelete ) {
237                std::list< Declaration * >::iterator i = declList.begin();
238                while ( i != declList.end() ) {
239                        std::list< Declaration * >::iterator next = i;
240                        ++next;
241                        if ( pred( *i ) ) {
242                                if ( doDelete ) {
243                                        delete *i;
244                                } // if
245                                declList.erase( i );
246                        } // if
247                        i = next;
248                } // while
249        }
250
251        bool isStructOrUnion( Declaration *decl ) {
252                return dynamic_cast< StructDecl * >( decl ) || dynamic_cast< UnionDecl * >( decl );
253        }
254
255        template< typename AggDecl >
256        void HoistStruct::handleAggregate( AggDecl *aggregateDecl ) {
257                if ( inStruct ) {
258                        // Add elements in stack order corresponding to nesting structure.
259                        declsToAdd.push_front( aggregateDecl );
260                        Visitor::visit( aggregateDecl );
261                } else {
262                        inStruct = true;
263                        Visitor::visit( aggregateDecl );
264                        inStruct = false;
265                } // if
266                // Always remove the hoisted aggregate from the inner structure.
267                filter( aggregateDecl->get_members(), isStructOrUnion, false );
268        }
269
270        void HoistStruct::visit( StructDecl *aggregateDecl ) {
271                handleAggregate( aggregateDecl );
272        }
273
274        void HoistStruct::visit( UnionDecl *aggregateDecl ) {
275                handleAggregate( aggregateDecl );
276        }
277
278        void HoistStruct::visit( CompoundStmt *compoundStmt ) {
279                addVisit( compoundStmt, *this );
280        }
281
282        void HoistStruct::visit( IfStmt *ifStmt ) {
283                addVisit( ifStmt, *this );
284        }
285
286        void HoistStruct::visit( WhileStmt *whileStmt ) {
287                addVisit( whileStmt, *this );
288        }
289
290        void HoistStruct::visit( ForStmt *forStmt ) {
291                addVisit( forStmt, *this );
292        }
293
294        void HoistStruct::visit( SwitchStmt *switchStmt ) {
295                addVisit( switchStmt, *this );
296        }
297
298        void HoistStruct::visit( ChooseStmt *switchStmt ) {
299                addVisit( switchStmt, *this );
300        }
301
302        void HoistStruct::visit( CaseStmt *caseStmt ) {
303                addVisit( caseStmt, *this );
304        }
305
306        void HoistStruct::visit( CatchStmt *cathStmt ) {
307                addVisit( cathStmt, *this );
308        }
309
310        void Pass1::visit( EnumDecl *enumDecl ) {
311                // Set the type of each member of the enumeration to be EnumConstant
312 
313                for ( std::list< Declaration * >::iterator i = enumDecl->get_members().begin(); i != enumDecl->get_members().end(); ++i ) {
314                        ObjectDecl * obj = dynamic_cast< ObjectDecl * >( *i );
315                        assert( obj );
316                        // obj->set_type( new EnumInstType( Type::Qualifiers( true, false, false, false, false, false ), enumDecl->get_name() ) );
317                        BasicType * enumType = new BasicType( Type::Qualifiers(), BasicType::SignedInt );
318                        obj->set_type( enumType ) ;
319                } // for
320                Parent::visit( enumDecl );
321        }
322
323        namespace {
324                template< typename DWTIterator >
325                void fixFunctionList( DWTIterator begin, DWTIterator end, FunctionType *func ) {
326                        // the only case in which "void" is valid is where it is the only one in the list; then it should be removed
327                        // entirely other fix ups are handled by the FixFunction class
328                        if ( begin == end ) return;
329                        FixFunction fixer;
330                        DWTIterator i = begin;
331                        *i = (*i )->acceptMutator( fixer );
332                        if ( fixer.get_isVoid() ) {
333                                DWTIterator j = i;
334                                ++i;
335                                func->get_parameters().erase( j );
336                                if ( i != end ) { 
337                                        throw SemanticError( "invalid type void in function type ", func );
338                                } // if
339                        } else {
340                                ++i;
341                                for ( ; i != end; ++i ) {
342                                        FixFunction fixer;
343                                        *i = (*i )->acceptMutator( fixer );
344                                        if ( fixer.get_isVoid() ) {
345                                                throw SemanticError( "invalid type void in function type ", func );
346                                        } // if
347                                } // for
348                        } // if
349                }
350        }
351
352        void Pass1::visit( FunctionType *func ) {
353                // Fix up parameters and return types
354                fixFunctionList( func->get_parameters().begin(), func->get_parameters().end(), func );
355                fixFunctionList( func->get_returnVals().begin(), func->get_returnVals().end(), func );
356                Visitor::visit( func );
357        }
358
359        Pass2::Pass2( bool doDebug, const Indexer *other_indexer ) : Indexer( doDebug ) {
360                if ( other_indexer ) {
361                        indexer = other_indexer;
362                } else {
363                        indexer = this;
364                } // if
365        }
366
367        void Pass2::visit( StructInstType *structInst ) {
368                Parent::visit( structInst );
369                StructDecl *st = indexer->lookupStruct( structInst->get_name() );
370                // it's not a semantic error if the struct is not found, just an implicit forward declaration
371                if ( st ) {
372                        assert( ! structInst->get_baseStruct() || structInst->get_baseStruct()->get_members().empty() || ! st->get_members().empty() );
373                        structInst->set_baseStruct( st );
374                } // if
375                if ( ! st || st->get_members().empty() ) {
376                        // use of forward declaration
377                        forwardStructs[ structInst->get_name() ].push_back( structInst );
378                } // if
379        }
380
381        void Pass2::visit( UnionInstType *unionInst ) {
382                Parent::visit( unionInst );
383                UnionDecl *un = indexer->lookupUnion( unionInst->get_name() );
384                // it's not a semantic error if the union is not found, just an implicit forward declaration
385                if ( un ) {
386                        unionInst->set_baseUnion( un );
387                } // if
388                if ( ! un || un->get_members().empty() ) {
389                        // use of forward declaration
390                        forwardUnions[ unionInst->get_name() ].push_back( unionInst );
391                } // if
392        }
393
394        void Pass2::visit( ContextInstType *contextInst ) {
395                Parent::visit( contextInst );
396                ContextDecl *ctx = indexer->lookupContext( contextInst->get_name() );
397                if ( ! ctx ) {
398                        throw SemanticError( "use of undeclared context " + contextInst->get_name() );
399                } // if
400                for ( std::list< TypeDecl * >::const_iterator i = ctx->get_parameters().begin(); i != ctx->get_parameters().end(); ++i ) {
401                        for ( std::list< DeclarationWithType * >::const_iterator assert = (*i )->get_assertions().begin(); assert != (*i )->get_assertions().end(); ++assert ) {
402                                if ( ContextInstType *otherCtx = dynamic_cast< ContextInstType * >(*assert ) ) {
403                                        cloneAll( otherCtx->get_members(), contextInst->get_members() );
404                                } else {
405                                        contextInst->get_members().push_back( (*assert )->clone() );
406                                } // if
407                        } // for
408                } // for
409
410                if ( ctx->get_parameters().size() != contextInst->get_parameters().size() ) {
411                        throw SemanticError( "incorrect number of context parameters: ", contextInst );
412                } // if
413
414                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() ) );
415        }
416
417        void Pass2::visit( StructDecl *structDecl ) {
418                if ( ! structDecl->get_members().empty() ) {
419                        ForwardStructsType::iterator fwds = forwardStructs.find( structDecl->get_name() );
420                        if ( fwds != forwardStructs.end() ) {
421                                for ( std::list< StructInstType * >::iterator inst = fwds->second.begin(); inst != fwds->second.end(); ++inst ) {
422                                        (*inst )->set_baseStruct( structDecl );
423                                } // for
424                                forwardStructs.erase( fwds );
425                        } // if
426                } // if
427                Indexer::visit( structDecl );
428        }
429
430        void Pass2::visit( UnionDecl *unionDecl ) {
431                if ( ! unionDecl->get_members().empty() ) {
432                        ForwardUnionsType::iterator fwds = forwardUnions.find( unionDecl->get_name() );
433                        if ( fwds != forwardUnions.end() ) {
434                                for ( std::list< UnionInstType * >::iterator inst = fwds->second.begin(); inst != fwds->second.end(); ++inst ) {
435                                        (*inst )->set_baseUnion( unionDecl );
436                                } // for
437                                forwardUnions.erase( fwds );
438                        } // if
439                } // if
440                Indexer::visit( unionDecl );
441        }
442
443        void Pass2::visit( TypeInstType *typeInst ) {
444                if ( NamedTypeDecl *namedTypeDecl = lookupType( typeInst->get_name() ) ) {
445                        if ( TypeDecl *typeDecl = dynamic_cast< TypeDecl * >( namedTypeDecl ) ) {
446                                typeInst->set_isFtype( typeDecl->get_kind() == TypeDecl::Ftype );
447                        } // if
448                } // if
449        }
450
451        Pass3::Pass3( const Indexer *other_indexer ) :  Indexer( false ) {
452                if ( other_indexer ) {
453                        indexer = other_indexer;
454                } else {
455                        indexer = this;
456                } // if
457        }
458
459        /// Fix up assertions
460        void forallFixer( Type *func ) {
461                for ( std::list< TypeDecl * >::iterator type = func->get_forall().begin(); type != func->get_forall().end(); ++type ) {
462                        std::list< DeclarationWithType * > toBeDone, nextRound;
463                        toBeDone.splice( toBeDone.end(), (*type )->get_assertions() );
464                        while ( ! toBeDone.empty() ) {
465                                for ( std::list< DeclarationWithType * >::iterator assertion = toBeDone.begin(); assertion != toBeDone.end(); ++assertion ) {
466                                        if ( ContextInstType *ctx = dynamic_cast< ContextInstType * >( (*assertion )->get_type() ) ) {
467                                                for ( std::list< Declaration * >::const_iterator i = ctx->get_members().begin(); i != ctx->get_members().end(); ++i ) {
468                                                        DeclarationWithType *dwt = dynamic_cast< DeclarationWithType * >( *i );
469                                                        assert( dwt );
470                                                        nextRound.push_back( dwt->clone() );
471                                                }
472                                                delete ctx;
473                                        } else {
474                                                FixFunction fixer;
475                                                *assertion = (*assertion )->acceptMutator( fixer );
476                                                if ( fixer.get_isVoid() ) {
477                                                        throw SemanticError( "invalid type void in assertion of function ", func );
478                                                }
479                                                (*type )->get_assertions().push_back( *assertion );
480                                        } // if
481                                } // for
482                                toBeDone.clear();
483                                toBeDone.splice( toBeDone.end(), nextRound );
484                        } // while
485                } // for
486        }
487
488        void Pass3::visit( ObjectDecl *object ) {
489                forallFixer( object->get_type() );
490                if ( PointerType *pointer = dynamic_cast< PointerType * >( object->get_type() ) ) {
491                        forallFixer( pointer->get_base() );
492                } // if
493                Parent::visit( object );
494                object->fixUniqueId();
495        }
496
497        void Pass3::visit( FunctionDecl *func ) {
498                forallFixer( func->get_type() );
499                Parent::visit( func );
500                func->fixUniqueId();
501        }
502
503        static const std::list< std::string > noLabels;
504
505        void AddStructAssignment::addStructAssignment( std::list< Declaration * > &translationUnit ) {
506                AddStructAssignment visitor;
507                acceptAndAdd( translationUnit, visitor, false );
508        }
509
510        template< typename OutputIterator >
511        void makeScalarAssignment( ObjectDecl *srcParam, ObjectDecl *dstParam, DeclarationWithType *member, OutputIterator out ) {
512                ObjectDecl *obj = dynamic_cast<ObjectDecl *>( member );
513                // unnamed bit fields are not copied as they cannot be accessed
514                if ( obj != NULL && obj->get_name() == "" && obj->get_bitfieldWidth() != NULL ) return;
515
516                UntypedExpr *assignExpr = new UntypedExpr( new NameExpr( "?=?" ) );
517 
518                UntypedExpr *derefExpr = new UntypedExpr( new NameExpr( "*?" ) );
519                derefExpr->get_args().push_back( new VariableExpr( dstParam ) );
520 
521                // do something special for unnamed members
522                Expression *dstselect = new AddressExpr( new MemberExpr( member, derefExpr ) );
523                assignExpr->get_args().push_back( dstselect );
524 
525                Expression *srcselect = new MemberExpr( member, new VariableExpr( srcParam ) );
526                assignExpr->get_args().push_back( srcselect );
527 
528                *out++ = new ExprStmt( noLabels, assignExpr );
529        }
530
531        template< typename OutputIterator >
532        void makeArrayAssignment( ObjectDecl *srcParam, ObjectDecl *dstParam, DeclarationWithType *member, ArrayType *array, OutputIterator out ) {
533                static UniqueName indexName( "_index" );
534 
535                // for a flexible array member nothing is done -- user must define own assignment
536                if ( ! array->get_dimension() ) return;
537 
538                ObjectDecl *index = new ObjectDecl( indexName.newName(), DeclarationNode::NoStorageClass, LinkageSpec::C, 0, new BasicType( Type::Qualifiers(), BasicType::SignedInt ), 0 );
539                *out++ = new DeclStmt( noLabels, index );
540 
541                UntypedExpr *init = new UntypedExpr( new NameExpr( "?=?" ) );
542                init->get_args().push_back( new AddressExpr( new VariableExpr( index ) ) );
543                init->get_args().push_back( new NameExpr( "0" ) );
544                Statement *initStmt = new ExprStmt( noLabels, init );
545                std::list<Statement *> initList;
546                initList.push_back( initStmt );
547 
548                UntypedExpr *cond = new UntypedExpr( new NameExpr( "?<?" ) );
549                cond->get_args().push_back( new VariableExpr( index ) );
550                cond->get_args().push_back( array->get_dimension()->clone() );
551 
552                UntypedExpr *inc = new UntypedExpr( new NameExpr( "++?" ) );
553                inc->get_args().push_back( new AddressExpr( new VariableExpr( index ) ) );
554 
555                UntypedExpr *assignExpr = new UntypedExpr( new NameExpr( "?=?" ) );
556 
557                UntypedExpr *derefExpr = new UntypedExpr( new NameExpr( "*?" ) );
558                derefExpr->get_args().push_back( new VariableExpr( dstParam ) );
559 
560                Expression *dstselect = new MemberExpr( member, derefExpr );
561                UntypedExpr *dstIndex = new UntypedExpr( new NameExpr( "?+?" ) );
562                dstIndex->get_args().push_back( dstselect );
563                dstIndex->get_args().push_back( new VariableExpr( index ) );
564                assignExpr->get_args().push_back( dstIndex );
565 
566                Expression *srcselect = new MemberExpr( member, new VariableExpr( srcParam ) );
567                UntypedExpr *srcIndex = new UntypedExpr( new NameExpr( "?[?]" ) );
568                srcIndex->get_args().push_back( srcselect );
569                srcIndex->get_args().push_back( new VariableExpr( index ) );
570                assignExpr->get_args().push_back( srcIndex );
571 
572                *out++ = new ForStmt( noLabels, initList, cond, inc, new ExprStmt( noLabels, assignExpr ) );
573        }
574
575        //E ?=?(E volatile*, int),
576        //  ?=?(E _Atomic volatile*, int);
577        void makeEnumAssignment( EnumDecl *enumDecl, EnumInstType *refType, unsigned int functionNesting, std::list< Declaration * > &declsToAdd ) {
578                FunctionType *assignType = new FunctionType( Type::Qualifiers(), false );
579 
580                ObjectDecl *returnVal = new ObjectDecl( "", DeclarationNode::NoStorageClass, LinkageSpec::Cforall, 0, refType->clone(), 0 );
581                assignType->get_returnVals().push_back( returnVal );
582
583                // need two assignment operators with different types
584                FunctionType * assignType2 = assignType->clone();
585
586                // E ?=?(E volatile *, E)
587                Type *etype = refType->clone();
588                // etype->get_qualifiers() += Type::Qualifiers(false, true, false, false, false, false);
589
590                ObjectDecl *dstParam = new ObjectDecl( "_dst", DeclarationNode::NoStorageClass, LinkageSpec::Cforall, 0, new PointerType( Type::Qualifiers(), etype ), 0 );
591                assignType->get_parameters().push_back( dstParam );
592
593                ObjectDecl *srcParam = new ObjectDecl( "_src", DeclarationNode::NoStorageClass, LinkageSpec::Cforall, 0, etype->clone(), 0 );
594                assignType->get_parameters().push_back( srcParam );
595
596                // E ?=?(E volatile *, int)
597                assignType2->get_parameters().push_back( dstParam->clone() );
598                BasicType * paramType = new BasicType(Type::Qualifiers(), BasicType::SignedInt); 
599                ObjectDecl *srcParam2 = new ObjectDecl( "_src", DeclarationNode::NoStorageClass, LinkageSpec::Cforall, 0, paramType, 0 );
600                assignType2->get_parameters().push_back( srcParam2 );
601
602                // Routines at global scope marked "static" to prevent multiple definitions is separate translation units
603                // because each unit generates copies of the default routines for each aggregate.
604
605                // since there is no definition, these should not be inline
606                // make these intrinsic so that the code generator does not make use of them
607                FunctionDecl *assignDecl = new FunctionDecl( "?=?", functionNesting > 0 ? DeclarationNode::NoStorageClass : DeclarationNode::Static, LinkageSpec::Intrinsic, assignType, 0, false, false );
608                assignDecl->fixUniqueId();
609                FunctionDecl *assignDecl2 = new FunctionDecl( "?=?", functionNesting > 0 ? DeclarationNode::NoStorageClass : DeclarationNode::Static, LinkageSpec::Intrinsic, assignType2, 0, false, false );
610                assignDecl2->fixUniqueId();
611
612                // these should be built in the same way that the prelude
613                // functions are, so build a list containing the prototypes
614                // and allow MakeLibCfa to autogenerate the bodies.
615                std::list< Declaration * > assigns;
616                assigns.push_back( assignDecl );
617                assigns.push_back( assignDecl2 );
618
619                LibCfa::makeLibCfa( assigns );
620
621                // need to remove the prototypes, since this may be nested in a routine
622                for (int start = 0, end = assigns.size()/2; start < end; start++) {
623                        delete assigns.front();
624                        assigns.pop_front();
625                } // for
626
627                declsToAdd.insert( declsToAdd.begin(), assigns.begin(), assigns.end() );
628        }
629
630
631        Declaration *makeStructAssignment( StructDecl *aggregateDecl, StructInstType *refType, unsigned int functionNesting ) {
632                FunctionType *assignType = new FunctionType( Type::Qualifiers(), false );
633 
634                ObjectDecl *returnVal = new ObjectDecl( "", DeclarationNode::NoStorageClass, LinkageSpec::Cforall, 0, refType->clone(), 0 );
635                assignType->get_returnVals().push_back( returnVal );
636 
637                ObjectDecl *dstParam = new ObjectDecl( "_dst", DeclarationNode::NoStorageClass, LinkageSpec::Cforall, 0, new PointerType( Type::Qualifiers(), refType->clone() ), 0 );
638                assignType->get_parameters().push_back( dstParam );
639 
640                ObjectDecl *srcParam = new ObjectDecl( "_src", DeclarationNode::NoStorageClass, LinkageSpec::Cforall, 0, refType, 0 );
641                assignType->get_parameters().push_back( srcParam );
642
643                // Routines at global scope marked "static" to prevent multiple definitions is separate translation units
644                // because each unit generates copies of the default routines for each aggregate.
645                FunctionDecl *assignDecl = new FunctionDecl( "?=?", functionNesting > 0 ? DeclarationNode::NoStorageClass : DeclarationNode::Static, LinkageSpec::AutoGen, assignType, new CompoundStmt( noLabels ), true, false );
646                assignDecl->fixUniqueId();
647 
648                for ( std::list< Declaration * >::const_iterator member = aggregateDecl->get_members().begin(); member != aggregateDecl->get_members().end(); ++member ) {
649                        if ( DeclarationWithType *dwt = dynamic_cast< DeclarationWithType * >( *member ) ) {
650                                // query the type qualifiers of this field and skip assigning it if it is marked const.
651                                // If it is an array type, we need to strip off the array layers to find its qualifiers.
652                                Type * type = dwt->get_type();
653                                while ( ArrayType * at = dynamic_cast< ArrayType * >( type ) ) {
654                                        type = at->get_base();
655                                }
656
657                                if ( type->get_qualifiers().isConst ) {
658                                        // don't assign const members
659                                        continue;
660                                }
661
662                                if ( ArrayType *array = dynamic_cast< ArrayType * >( dwt->get_type() ) ) {
663                                        makeArrayAssignment( srcParam, dstParam, dwt, array, back_inserter( assignDecl->get_statements()->get_kids() ) );
664                                } else {
665                                        makeScalarAssignment( srcParam, dstParam, dwt, back_inserter( assignDecl->get_statements()->get_kids() ) );
666                                } // if
667                        } // if
668                } // for
669                assignDecl->get_statements()->get_kids().push_back( new ReturnStmt( noLabels, new VariableExpr( srcParam ) ) );
670 
671                return assignDecl;
672        }
673
674        Declaration *makeUnionAssignment( UnionDecl *aggregateDecl, UnionInstType *refType, unsigned int functionNesting ) {
675                FunctionType *assignType = new FunctionType( Type::Qualifiers(), false );
676 
677                ObjectDecl *returnVal = new ObjectDecl( "", DeclarationNode::NoStorageClass, LinkageSpec::Cforall, 0, refType->clone(), 0 );
678                assignType->get_returnVals().push_back( returnVal );
679 
680                ObjectDecl *dstParam = new ObjectDecl( "_dst", DeclarationNode::NoStorageClass, LinkageSpec::Cforall, 0, new PointerType( Type::Qualifiers(), refType->clone() ), 0 );
681                assignType->get_parameters().push_back( dstParam );
682 
683                ObjectDecl *srcParam = new ObjectDecl( "_src", DeclarationNode::NoStorageClass, LinkageSpec::Cforall, 0, refType, 0 );
684                assignType->get_parameters().push_back( srcParam );
685 
686                // Routines at global scope marked "static" to prevent multiple definitions is separate translation units
687                // because each unit generates copies of the default routines for each aggregate.
688                FunctionDecl *assignDecl = new FunctionDecl( "?=?",  functionNesting > 0 ? DeclarationNode::NoStorageClass : DeclarationNode::Static, LinkageSpec::AutoGen, assignType, new CompoundStmt( noLabels ), true, false );
689                assignDecl->fixUniqueId();
690 
691                UntypedExpr *copy = new UntypedExpr( new NameExpr( "__builtin_memcpy" ) );
692                copy->get_args().push_back( new VariableExpr( dstParam ) );
693                copy->get_args().push_back( new AddressExpr( new VariableExpr( srcParam ) ) );
694                copy->get_args().push_back( new SizeofExpr( refType->clone() ) );
695
696                assignDecl->get_statements()->get_kids().push_back( new ExprStmt( noLabels, copy ) );
697                assignDecl->get_statements()->get_kids().push_back( new ReturnStmt( noLabels, new VariableExpr( srcParam ) ) );
698 
699                return assignDecl;
700        }
701
702        void AddStructAssignment::visit( EnumDecl *enumDecl ) {
703                if ( ! enumDecl->get_members().empty() ) {
704                        EnumInstType *enumInst = new EnumInstType( Type::Qualifiers(), enumDecl->get_name() );
705                        // enumInst->set_baseEnum( enumDecl );
706                        // declsToAdd.push_back(
707                        makeEnumAssignment( enumDecl, enumInst, functionNesting, declsToAdd );
708                }
709        }
710
711        void AddStructAssignment::visit( StructDecl *structDecl ) {
712                if ( ! structDecl->get_members().empty() && structsDone.find( structDecl->get_name() ) == structsDone.end() ) {
713                        StructInstType *structInst = new StructInstType( Type::Qualifiers(), structDecl->get_name() );
714                        structInst->set_baseStruct( structDecl );
715                        declsToAdd.push_back( makeStructAssignment( structDecl, structInst, functionNesting ) );
716                        structsDone.insert( structDecl->get_name() );
717                } // if
718        }
719
720        void AddStructAssignment::visit( UnionDecl *unionDecl ) {
721                if ( ! unionDecl->get_members().empty() ) {
722                        UnionInstType *unionInst = new UnionInstType( Type::Qualifiers(), unionDecl->get_name() );
723                        unionInst->set_baseUnion( unionDecl );
724                        declsToAdd.push_back( makeUnionAssignment( unionDecl, unionInst, functionNesting ) );
725                } // if
726        }
727
728        void AddStructAssignment::visit( TypeDecl *typeDecl ) {
729                CompoundStmt *stmts = 0;
730                TypeInstType *typeInst = new TypeInstType( Type::Qualifiers(), typeDecl->get_name(), false );
731                typeInst->set_baseType( typeDecl );
732                ObjectDecl *src = new ObjectDecl( "_src", DeclarationNode::NoStorageClass, LinkageSpec::Cforall, 0, typeInst->clone(), 0 );
733                ObjectDecl *dst = new ObjectDecl( "_dst", DeclarationNode::NoStorageClass, LinkageSpec::Cforall, 0, new PointerType( Type::Qualifiers(), typeInst->clone() ), 0 );
734                if ( typeDecl->get_base() ) {
735                        stmts = new CompoundStmt( std::list< Label >() );
736                        UntypedExpr *assign = new UntypedExpr( new NameExpr( "?=?" ) );
737                        assign->get_args().push_back( new CastExpr( new VariableExpr( dst ), new PointerType( Type::Qualifiers(), typeDecl->get_base()->clone() ) ) );
738                        assign->get_args().push_back( new CastExpr( new VariableExpr( src ), typeDecl->get_base()->clone() ) );
739                        stmts->get_kids().push_back( new ReturnStmt( std::list< Label >(), assign ) );
740                } // if
741                FunctionType *type = new FunctionType( Type::Qualifiers(), false );
742                type->get_returnVals().push_back( new ObjectDecl( "", DeclarationNode::NoStorageClass, LinkageSpec::Cforall, 0, typeInst, 0 ) );
743                type->get_parameters().push_back( dst );
744                type->get_parameters().push_back( src );
745                FunctionDecl *func = new FunctionDecl( "?=?", DeclarationNode::NoStorageClass, LinkageSpec::AutoGen, type, stmts, false, false );
746                declsToAdd.push_back( func );
747        }
748
749        void addDecls( std::list< Declaration * > &declsToAdd, std::list< Statement * > &statements, std::list< Statement * >::iterator i ) {
750                for ( std::list< Declaration * >::iterator decl = declsToAdd.begin(); decl != declsToAdd.end(); ++decl ) {
751                        statements.insert( i, new DeclStmt( noLabels, *decl ) );
752                } // for
753                declsToAdd.clear();
754        }
755
756        void AddStructAssignment::visit( FunctionType *) {
757                // ensure that we don't add assignment ops for types defined as part of the function
758        }
759
760        void AddStructAssignment::visit( PointerType *) {
761                // ensure that we don't add assignment ops for types defined as part of the pointer
762        }
763
764        void AddStructAssignment::visit( ContextDecl *) {
765                // ensure that we don't add assignment ops for types defined as part of the context
766        }
767
768        template< typename StmtClass >
769        inline void AddStructAssignment::visitStatement( StmtClass *stmt ) {
770                std::set< std::string > oldStructs = structsDone;
771                addVisit( stmt, *this );
772                structsDone = oldStructs;
773        }
774
775        void AddStructAssignment::visit( FunctionDecl *functionDecl ) {
776                maybeAccept( functionDecl->get_functionType(), *this );
777                acceptAll( functionDecl->get_oldDecls(), *this );
778                functionNesting += 1;
779                maybeAccept( functionDecl->get_statements(), *this );
780                functionNesting -= 1;
781        }
782
783        void AddStructAssignment::visit( CompoundStmt *compoundStmt ) {
784                visitStatement( compoundStmt );
785        }
786
787        void AddStructAssignment::visit( IfStmt *ifStmt ) {
788                visitStatement( ifStmt );
789        }
790
791        void AddStructAssignment::visit( WhileStmt *whileStmt ) {
792                visitStatement( whileStmt );
793        }
794
795        void AddStructAssignment::visit( ForStmt *forStmt ) {
796                visitStatement( forStmt );
797        }
798
799        void AddStructAssignment::visit( SwitchStmt *switchStmt ) {
800                visitStatement( switchStmt );
801        }
802
803        void AddStructAssignment::visit( ChooseStmt *switchStmt ) {
804                visitStatement( switchStmt );
805        }
806
807        void AddStructAssignment::visit( CaseStmt *caseStmt ) {
808                visitStatement( caseStmt );
809        }
810
811        void AddStructAssignment::visit( CatchStmt *cathStmt ) {
812                visitStatement( cathStmt );
813        }
814
815        bool isTypedef( Declaration *decl ) {
816                return dynamic_cast< TypedefDecl * >( decl );
817        }
818
819        void EliminateTypedef::eliminateTypedef( std::list< Declaration * > &translationUnit ) {
820                EliminateTypedef eliminator;
821                mutateAll( translationUnit, eliminator );
822                filter( translationUnit, isTypedef, true );
823        }
824
825        Type *EliminateTypedef::mutate( TypeInstType * typeInst ) {
826                // instances of typedef types will come here. If it is an instance
827                // of a typdef type, link the instance to its actual type.
828                TypedefMap::const_iterator def = typedefNames.find( typeInst->get_name() );
829                if ( def != typedefNames.end() ) {
830                        Type *ret = def->second.first->get_base()->clone();
831                        ret->get_qualifiers() += typeInst->get_qualifiers();
832                        // place instance parameters on the typedef'd type
833                        if ( ! typeInst->get_parameters().empty() ) {
834                                ReferenceToType *rtt = dynamic_cast<ReferenceToType*>(ret);
835                                if ( ! rtt ) {
836                                        throw SemanticError("cannot apply type parameters to base type of " + typeInst->get_name());
837                                }
838                                rtt->get_parameters().clear();
839                                cloneAll(typeInst->get_parameters(), rtt->get_parameters());
840                        } // if
841                        delete typeInst;
842                        return ret;
843                } else {
844                        TypeDeclMap::const_iterator base = typedeclNames.find( typeInst->get_name() );
845                        assert( base != typedeclNames.end() );
846                        typeInst->set_baseType( base->second->clone() );
847                } // if
848                return typeInst;
849        }
850
851        Declaration *EliminateTypedef::mutate( TypedefDecl * tyDecl ) {
852                Declaration *ret = Mutator::mutate( tyDecl );
853                if ( typedefNames.count( tyDecl->get_name() ) == 1 && typedefNames[ tyDecl->get_name() ].second == scopeLevel ) {
854                        // typedef to the same name from the same scope
855                        // must be from the same type
856
857                        Type * t1 = tyDecl->get_base();
858                        Type * t2 = typedefNames[ tyDecl->get_name() ].first->get_base();
859                        if ( ! typeEquals( t1, t2, true ) ) {
860                                throw SemanticError( "cannot redefine typedef: " + tyDecl->get_name() );
861                        }
862                } else {
863                        typedefNames[ tyDecl->get_name() ] = std::make_pair( tyDecl, scopeLevel );
864                } // if
865
866                // When a typedef is a forward declaration:
867                //    typedef struct screen SCREEN;
868                // the declaration portion must be retained:
869                //    struct screen;
870                // because the expansion of the typedef is:
871                //    void rtn( SCREEN *p ) => void rtn( struct screen *p )
872                // hence the type-name "screen" must be defined.
873                // Note, qualifiers on the typedef are superfluous for the forward declaration.
874                if ( StructInstType *aggDecl = dynamic_cast< StructInstType * >( tyDecl->get_base() ) ) {
875                        return new StructDecl( aggDecl->get_name() );
876                } else if ( UnionInstType *aggDecl = dynamic_cast< UnionInstType * >( tyDecl->get_base() ) ) {
877                        return new UnionDecl( aggDecl->get_name() );
878                } else {
879                        return ret;
880                } // if
881        }
882
883        TypeDecl *EliminateTypedef::mutate( TypeDecl * typeDecl ) {
884                TypedefMap::iterator i = typedefNames.find( typeDecl->get_name() );
885                if ( i != typedefNames.end() ) {
886                        typedefNames.erase( i ) ;
887                } // if
888
889                typedeclNames[ typeDecl->get_name() ] = typeDecl;
890                return typeDecl;
891        }
892
893        DeclarationWithType *EliminateTypedef::mutate( FunctionDecl * funcDecl ) {
894                TypedefMap oldNames = typedefNames;
895                DeclarationWithType *ret = Mutator::mutate( funcDecl );
896                typedefNames = oldNames;
897                return ret;
898        }
899
900        DeclarationWithType *EliminateTypedef::mutate( ObjectDecl * objDecl ) {
901                TypedefMap oldNames = typedefNames;
902                DeclarationWithType *ret = Mutator::mutate( objDecl );
903                typedefNames = oldNames;
904                if ( FunctionType *funtype = dynamic_cast<FunctionType *>( ret->get_type() ) ) {
905                        return new FunctionDecl( ret->get_name(), ret->get_storageClass(), ret->get_linkage(), funtype, 0, ret->get_isInline(), ret->get_isNoreturn() );
906                } else if ( objDecl->get_isInline() || objDecl->get_isNoreturn() ) {
907                        throw SemanticError( "invalid inline or _Noreturn specification in declaration of ", objDecl );
908                } // if
909                return ret;
910        }
911
912        Expression *EliminateTypedef::mutate( CastExpr * castExpr ) {
913                TypedefMap oldNames = typedefNames;
914                Expression *ret = Mutator::mutate( castExpr );
915                typedefNames = oldNames;
916                return ret;
917        }
918
919        CompoundStmt *EliminateTypedef::mutate( CompoundStmt * compoundStmt ) {
920                TypedefMap oldNames = typedefNames;
921                scopeLevel += 1;
922                CompoundStmt *ret = Mutator::mutate( compoundStmt );
923                scopeLevel -= 1;
924                std::list< Statement * >::iterator i = compoundStmt->get_kids().begin();
925                while ( i != compoundStmt->get_kids().end() ) {
926                        std::list< Statement * >::iterator next = i+1;
927                        if ( DeclStmt *declStmt = dynamic_cast< DeclStmt * >( *i ) ) {
928                                if ( dynamic_cast< TypedefDecl * >( declStmt->get_decl() ) ) {
929                                        delete *i;
930                                        compoundStmt->get_kids().erase( i );
931                                } // if
932                        } // if
933                        i = next;
934                } // while
935                typedefNames = oldNames;
936                return ret;
937        }
938
939        // there may be typedefs nested within aggregates
940        // in order for everything to work properly, these
941        // should be removed as well
942        template<typename AggDecl>
943        AggDecl *EliminateTypedef::handleAggregate( AggDecl * aggDecl ) {
944                std::list<Declaration *>::iterator it = aggDecl->get_members().begin();
945                for ( ; it != aggDecl->get_members().end(); ) {
946                        std::list< Declaration * >::iterator next = it+1;
947                        if ( dynamic_cast< TypedefDecl * >( *it ) ) {
948                                delete *it;
949                                aggDecl->get_members().erase( it );
950                        } // if
951                        it = next;
952                }
953                return aggDecl;
954        }
955
956        Declaration *EliminateTypedef::mutate( StructDecl * structDecl ) {
957                Mutator::mutate( structDecl );
958                return handleAggregate( structDecl );
959        }
960
961        Declaration *EliminateTypedef::mutate( UnionDecl * unionDecl ) {
962                Mutator::mutate( unionDecl );
963                return handleAggregate( unionDecl );
964        }
965
966        Declaration *EliminateTypedef::mutate( EnumDecl * enumDecl ) {
967                Mutator::mutate( enumDecl );
968                return handleAggregate( enumDecl );
969        }
970
971                Declaration *EliminateTypedef::mutate( ContextDecl * contextDecl ) {
972                Mutator::mutate( contextDecl );
973                return handleAggregate( contextDecl );
974        }
975
976} // namespace SymTab
977
978// Local Variables: //
979// tab-width: 4 //
980// mode: c++ //
981// compile-command: "make install" //
982// End: //
Note: See TracBrowser for help on using the repository browser.