source: src/Validate/ReplaceTypedef.cpp @ 0bd46fd

ADTast-experimentalpthread-emulation
Last change on this file since 0bd46fd was 0bd46fd, checked in by Thierry Delisle <tdelisle@…>, 20 months ago

Fixed several warnings

  • Property mode set to 100644
File size: 12.4 KB
Line 
1//
2// Cforall Version 1.0.0 Copyright (C) 2018 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// ReplaceTypedef.cpp -- Fill in all typedefs with the underlying type.
8//
9// Author           : Andrew Beach
10// Created On       : Tue Jun 29 14:59:00 2022
11// Last Modified By : Andrew Beach
12// Last Modified On : Tue Sep 20 17:00:00 2022
13// Update Count     : 2
14//
15
16#include "ReplaceTypedef.hpp"
17
18#include "AST/Pass.hpp"
19#include "Common/ScopedMap.h"
20#include "Common/UniqueName.h"
21#include "Common/utility.h"
22#include "ResolvExpr/typeops.h"
23
24namespace Validate {
25
26namespace {
27
28bool isNonParameterAttribute( ast::Attribute const * attr ) {
29        static const std::vector<std::string> bad_names = {
30                "aligned", "__aligned__",
31        };
32        for ( auto name : bad_names ) {
33                if ( name == attr->name ) {
34                        return true;
35                }
36        }
37        return false;
38}
39
40struct ReplaceTypedefCore final :
41                public ast::WithCodeLocation,
42                public ast::WithDeclsToAdd<>,
43                public ast::WithGuards,
44                public ast::WithShortCircuiting,
45                public ast::WithVisitorRef<ReplaceTypedefCore> {
46
47        void previsit( ast::QualifiedType const * );
48        ast::Type const * postvisit( ast::QualifiedType const * );
49        ast::Type const * postvisit( ast::TypeInstType const * );
50        ast::Decl const * postvisit( ast::TypedefDecl const * );
51        void previsit( ast::TypeDecl const * );
52        void previsit( ast::FunctionDecl const * );
53        void previsit( ast::ObjectDecl const * );
54        ast::DeclWithType const * postvisit( ast::ObjectDecl const * );
55
56        void previsit( ast::CastExpr const * );
57        void previsit( ast::CompoundStmt const * );
58        void postvisit( ast::CompoundStmt const * );
59
60        ast::StructDecl const * previsit( ast::StructDecl const * );
61        ast::UnionDecl const * previsit( ast::UnionDecl const * );
62        void previsit( ast::EnumDecl const * );
63        void previsit( ast::TraitDecl const * );
64
65        template<typename AggrDecl>
66        void addImplicitTypedef( AggrDecl * aggDecl );
67        template<typename AggrDecl>
68        AggrDecl const * handleAggregate( AggrDecl const * aggDecl );
69
70        using TypedefDeclPtr = ast::ptr<ast::TypedefDecl>;
71        using TypedefMap = ScopedMap<std::string, std::pair<TypedefDeclPtr, int>>;
72        using TypeDeclMap = ScopedMap<std::string, ast::TypeDecl const *>;
73
74        TypedefMap typedefNames;
75        TypeDeclMap typedeclNames;
76        int scopeLevel;
77        bool isAtFunctionTop = false;
78};
79
80void ReplaceTypedefCore::previsit( ast::QualifiedType const * ) {
81        visit_children = false;
82}
83
84ast::Type const * ReplaceTypedefCore::postvisit(
85                ast::QualifiedType const * type ) {
86        // Replacing typedefs only makes sense for the 'oldest ancestor'
87        // of the qualified type.
88        return ast::mutate_field( type, &ast::QualifiedType::parent,
89                type->parent->accept( *visitor ) );
90}
91
92ast::Type const * ReplaceTypedefCore::postvisit(
93                ast::TypeInstType const * type ) {
94        // Instances of typedef types will come here. If it is an instance
95        // of a typedef type, link the instance to its actual type.
96        TypedefMap::const_iterator def = typedefNames.find( type->name );
97        if ( def != typedefNames.end() ) {
98                ast::Type * ret = ast::deepCopy( def->second.first->base );
99                ret->qualifiers |= type->qualifiers;
100                // We ignore certain attributes on function parameters if they arrive
101                // by typedef. GCC appears to do the same thing.
102                if ( isAtFunctionTop ) {
103                        erase_if( ret->attributes, isNonParameterAttribute );
104                }
105                for ( const auto & attribute : type->attributes ) {
106                        ret->attributes.push_back( attribute );
107                }
108                // Place instance parameters on the typedef'd type.
109                if ( !type->params.empty() ) {
110                        auto rtt = dynamic_cast<ast::BaseInstType *>( ret );
111                        if ( !rtt ) {
112                                assert( location );
113                                SemanticError( *location, "Cannot apply type parameters to base type of " + type->name );
114                        }
115                        rtt->params.clear();
116                        for ( auto it : type->params ) {
117                                rtt->params.push_back( ast::deepCopy( it ) );
118                        }
119                        // Recursively fix typedefs on parameters.
120                        ast::mutate_each( rtt, &ast::BaseInstType::params, *visitor );
121                }
122                return ret;
123        } else {
124                TypeDeclMap::const_iterator base = typedeclNames.find( type->name );
125                if ( base == typedeclNames.end() ) {
126                        assert( location );
127                        SemanticError( *location, toString( "Use of undefined type ", type->name ) );
128                }
129                return ast::mutate_field( type, &ast::TypeInstType::base, base->second );
130        }
131}
132
133struct VarLenChecker : public ast::WithShortCircuiting {
134        bool result = false;
135        void previsit( ast::FunctionType const * ) { visit_children = false; }
136        void previsit( ast::ArrayType const * at ) { result |= at->isVarLen; }
137};
138
139ast::Decl const * ReplaceTypedefCore::postvisit(
140                ast::TypedefDecl const * decl ) {
141        if ( 1 == typedefNames.count( decl->name ) &&
142                        typedefNames[ decl->name ].second == scopeLevel ) {
143                ast::Type const * t0 = decl->base;
144                ast::Type const * t1 = typedefNames[ decl->name ].first->base;
145                // Cannot redefine VLA typedefs. Note: this is slightly incorrect,
146                // because our notion of VLAs at this point in the translator is
147                // imprecise. In particular, this will disallow redefining typedefs
148                // with arrays whose dimension is an enumerator or a cast of a
149                // constant/enumerator. The effort required to fix this corner case
150                // likely outweighs the utility of allowing it.
151                if ( !ResolvExpr::typesCompatible( t0, t1, ast::SymbolTable() )
152                                || ast::Pass<VarLenChecker>::read( t0 )
153                                || ast::Pass<VarLenChecker>::read( t1 ) ) {
154                        SemanticError( decl->location, "Cannot redefine typedef: " + decl->name );
155                }
156        } else {
157                typedefNames[ decl->name ] =
158                        std::make_pair( TypedefDeclPtr( decl ), scopeLevel );
159        }
160
161        // When a typedef is a forward declaration:
162        // >    typedef struct screen SCREEN;
163        // the declaration portion must be retained:
164        // >    struct screen;
165        // because the expansion of the typedef is:
166        // >    void func( SCREEN * p ) -> void func( struct screen * p );
167        // hence type name "screen" must be defined.
168        // Note: qualifiers on the typedef are not used for the forward declaration.
169
170        ast::Type const * designatorType = decl->base->stripDeclarator();
171        if ( auto structType = dynamic_cast<ast::StructInstType const *>( designatorType ) ) {
172                declsToAddBefore.push_back( new ast::StructDecl(
173                        decl->location, structType->name, ast::AggregateDecl::Struct, {},
174                        decl->linkage ) );
175        } else if ( auto unionType = dynamic_cast<ast::UnionInstType const *>( designatorType ) ) {
176                declsToAddBefore.push_back( new ast::UnionDecl(
177                        decl->location, unionType->name, {}, decl->linkage ) );
178        } else if ( auto enumType = dynamic_cast<ast::EnumInstType const *>( designatorType ) ) {
179                declsToAddBefore.push_back( new ast::EnumDecl(
180                        decl->location, enumType->name, false, {}, decl->linkage,
181                        ( (enumType->base) ? enumType->base->base : nullptr )
182                        ) );
183        }
184        return ast::deepCopy( decl );
185}
186
187void ReplaceTypedefCore::previsit( ast::TypeDecl const * decl ) {
188        TypedefMap::iterator iter = typedefNames.find( decl->name );
189        if ( iter != typedefNames.end() ) {
190                typedefNames.erase( iter );
191        }
192        typedeclNames.insert( decl->name, decl );
193}
194
195void ReplaceTypedefCore::previsit( ast::FunctionDecl const * ) {
196        GuardScope( typedefNames );
197        GuardScope( typedeclNames );
198        GuardValue( isAtFunctionTop ) = true;
199}
200
201void ReplaceTypedefCore::previsit( ast::ObjectDecl const * ) {
202        GuardScope( typedefNames );
203        GuardScope( typedeclNames );
204}
205
206ast::DeclWithType const * ReplaceTypedefCore::postvisit(
207                ast::ObjectDecl const * decl ) {
208        if ( ast::FunctionType const * type = decl->type.as<ast::FunctionType>() ) {
209                using DWTVector = std::vector<ast::ptr<ast::DeclWithType>>;
210                using DeclVector = std::vector<ast::ptr<ast::TypeDecl>>;
211                CodeLocation const & declLocation = decl->location;
212                UniqueName paramNamer( decl->name + "Param" );
213
214                // Replace the current object declaration with a function declaration.
215                ast::FunctionDecl const * newDecl = new ast::FunctionDecl(
216                        declLocation,
217                        decl->name,
218                        map_range<DeclVector>( type->forall, []( const ast::TypeInstType * inst ) {
219                                return ast::deepCopy( inst->base );
220                        } ),
221                        map_range<DWTVector>( type->assertions, []( const ast::VariableExpr * expr ) {
222                                return ast::deepCopy( expr->var );
223                        } ),
224                        map_range<DWTVector>( type->params, [&declLocation, &paramNamer]( const ast::Type * type ) {
225                                assert( type );
226                                return new ast::ObjectDecl( declLocation, paramNamer.newName(), ast::deepCopy( type ) );
227                        } ),
228                        map_range<DWTVector>( type->returns, [&declLocation, &paramNamer]( const ast::Type * type ) {
229                                assert( type );
230                                return new ast::ObjectDecl( declLocation, paramNamer.newName(), ast::deepCopy( type ) );
231                        } ),
232                        nullptr,
233                        decl->storage,
234                        decl->linkage,
235                        {/* attributes */},
236                        decl->funcSpec
237                );
238                return newDecl;
239        }
240        return decl;
241}
242
243void ReplaceTypedefCore::previsit( ast::CastExpr const * ) {
244        GuardScope( typedefNames );
245        GuardScope( typedeclNames );
246}
247
248void ReplaceTypedefCore::previsit( ast::CompoundStmt const * ) {
249        GuardScope( typedefNames );
250        GuardScope( typedeclNames );
251        GuardValue( isAtFunctionTop ) = false;
252        scopeLevel += 1;
253}
254
255void ReplaceTypedefCore::postvisit( ast::CompoundStmt const * ) {
256        scopeLevel -= 1;
257}
258
259ast::StructDecl const * ReplaceTypedefCore::previsit( ast::StructDecl const * decl ) {
260        visit_children = false;
261        addImplicitTypedef( decl );
262        return handleAggregate( decl );
263}
264
265ast::UnionDecl const * ReplaceTypedefCore::previsit( ast::UnionDecl const * decl ) {
266        visit_children = false;
267        addImplicitTypedef( decl );
268        return handleAggregate( decl );
269}
270
271void ReplaceTypedefCore::previsit( ast::EnumDecl const * decl ) {
272        addImplicitTypedef( decl );
273}
274
275void ReplaceTypedefCore::previsit( ast::TraitDecl const * ) {
276        GuardScope( typedefNames );
277        GuardScope( typedeclNames );
278}
279
280template<typename AggrDecl>
281void ReplaceTypedefCore::addImplicitTypedef( AggrDecl * aggrDecl ) {
282        if ( 0 != typedefNames.count( aggrDecl->name ) ) {
283                return;
284        }
285        ast::Type * type = nullptr;
286        if ( auto structDecl = dynamic_cast<const ast::StructDecl *>( aggrDecl ) ) {
287                type = new ast::StructInstType( structDecl->name );
288        } else if ( auto unionDecl = dynamic_cast<const ast::UnionDecl *>( aggrDecl ) ) {
289                type = new ast::UnionInstType( unionDecl->name );
290        } else if ( auto enumDecl = dynamic_cast<const ast::EnumDecl *>( aggrDecl ) ) {
291                type = new ast::EnumInstType( enumDecl->name );
292        }
293        assert( type );
294
295        TypedefDeclPtr typeDecl = new ast::TypedefDecl( aggrDecl->location,
296                aggrDecl->name, ast::Storage::Classes(), type, aggrDecl->linkage );
297        // Add the implicit typedef to the AST.
298        declsToAddBefore.push_back( ast::deepCopy( typeDecl.get() ) );
299        // Shore the name in the map of names.
300        typedefNames[ aggrDecl->name ] =
301                std::make_pair( std::move( typeDecl ), scopeLevel );
302}
303
304template<typename AggrDecl>
305AggrDecl const * ReplaceTypedefCore::handleAggregate( AggrDecl const * decl ) {
306        SemanticErrorException errors;
307
308        ValueGuard<decltype(declsToAddBefore)> oldBeforeDecls( declsToAddBefore );
309        ValueGuard<decltype(declsToAddAfter )> oldAfterDecls(  declsToAddAfter );
310        declsToAddBefore.clear();
311        declsToAddAfter.clear();
312
313        GuardScope( typedefNames );
314        GuardScope( typedeclNames );
315        decl = mutate_each( decl, &ast::AggregateDecl::params, *visitor );
316        decl = mutate_each( decl, &ast::AggregateDecl::attributes, *visitor );
317
318        auto mut = ast::mutate( decl );
319
320        std::vector<ast::ptr<ast::Decl>> members;
321        // Unroll accept_all for decl->members so that implicit typedefs for
322        // nested types are added to the aggregate body.
323        for ( ast::ptr<ast::Decl> const & member : mut->members ) {
324                assert( declsToAddAfter.empty() );
325                ast::Decl const * newMember = nullptr;
326                try {
327                        newMember = member->accept( *visitor );
328                } catch ( SemanticErrorException & e ) {
329                        errors.append( e );
330                }
331                if ( !declsToAddBefore.empty() ) {
332                        for ( auto declToAdd : declsToAddBefore ) {
333                                members.push_back( declToAdd );
334                        }
335                        declsToAddBefore.clear();
336                }
337                members.push_back( newMember );
338        }
339        assert( declsToAddAfter.empty() );
340        if ( !errors.isEmpty() ) { throw errors; }
341
342        mut->members.clear();
343        for ( auto member : members ) {
344                mut->members.push_back( member );
345        }
346
347        return mut;
348}
349
350} // namespace
351
352void replaceTypedef( ast::TranslationUnit & translationUnit ) {
353        ast::Pass<ReplaceTypedefCore> pass;
354        ast::accept_all( translationUnit, pass );
355        if ( pass.core.typedefNames.count( "size_t" ) ) {
356                translationUnit.global.sizeType =
357                        ast::deepCopy( pass.core.typedefNames["size_t"].first->base );
358        } else {
359                // Missing the global definition, default to long unsigned int.
360                // Perhaps this should be a warning instead.
361                translationUnit.global.sizeType =
362                        new ast::BasicType( ast::BasicType::LongUnsignedInt );
363        }
364}
365
366} // namespace Validate
367
368// Local Variables: //
369// tab-width: 4 //
370// mode: c++ //
371// compile-command: "make install" //
372// End: //
Note: See TracBrowser for help on using the repository browser.