source: src/AST/SymbolTable.cpp @ 3e5dd913

ADTarm-ehast-experimentalenumforall-pointer-decayjacob/cs343-translationnew-ast-unique-exprpthread-emulationqualifiedEnum
Last change on this file since 3e5dd913 was 3e5dd913, checked in by Fangren Yu <f37yu@…>, 3 years ago

reimplement function type and eliminate deep copy

  • Property mode set to 100644
File size: 27.5 KB
RevLine 
[d76c588]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// SymbolTable.cpp --
8//
9// Author           : Aaron B. Moss
10// Created On       : Wed May 29 11:00:00 2019
11// Last Modified By : Aaron B. Moss
12// Last Modified On : Wed May 29 11:00:00 2019
13// Update Count     : 1
14//
15
16#include "SymbolTable.hpp"
17
18#include <cassert>
19
20#include "Decl.hpp"
21#include "Expr.hpp"
22#include "Type.hpp"
23#include "CodeGen/OperatorTable.h"  // for isCtorDtorAssign
24#include "Common/SemanticError.h"
25#include "Common/Stats/Counter.h"
26#include "GenPoly/GenPoly.h"
27#include "InitTweak/InitTweak.h"
28#include "ResolvExpr/Cost.h"
29#include "ResolvExpr/typeops.h"
30#include "SymTab/Mangler.h"
31
32namespace ast {
33
34// Statistics block
35namespace {
36        static inline auto stats() {
37                using namespace Stats::Counters;
38                static auto group   = build<CounterGroup>("Indexers");
39                static struct {
40                        SimpleCounter * count;
41                        AverageCounter<double> * size;
42                        SimpleCounter * new_scopes;
43                        SimpleCounter * lazy_scopes;
44                        AverageCounter<double> * avg_scope_depth;
45                        MaxCounter<size_t> * max_scope_depth;
46                        SimpleCounter * add_calls;
47                        SimpleCounter * lookup_calls;
48                        SimpleCounter * map_lookups;
49                        SimpleCounter * map_mutations;
50                } ret = {
51                        .count   = build<SimpleCounter>("Count", group),
52                        .size    = build<AverageCounter<double>>("Average Size", group),
53                        .new_scopes = build<SimpleCounter>("Scopes", group),
54                        .lazy_scopes = build<SimpleCounter>("Lazy Scopes", group),
55                        .avg_scope_depth = build<AverageCounter<double>>("Average Scope", group),
56                        .max_scope_depth = build<MaxCounter<size_t>>("Max Scope", group),
57                        .add_calls = build<SimpleCounter>("Add Calls", group),
58                        .lookup_calls = build<SimpleCounter>("Lookup Calls", group),
59                        .map_lookups = build<SimpleCounter>("Map Lookups", group),
60                        .map_mutations = build<SimpleCounter>("Map Mutations", group)
61                };
62                return ret;
63        }
64}
65
66Expr * SymbolTable::IdData::combine( const CodeLocation & loc, ResolvExpr::Cost & cost ) const {
67        Expr * ret = ( baseExpr ) ?
68                (Expr *)new MemberExpr{ loc, id, referenceToRvalueConversion( baseExpr, cost ) } :
69                (Expr *)new VariableExpr{ loc, id };
70        if ( deleter ) { ret = new DeletedExpr{ loc, ret, deleter }; }
71        return ret;
72}
73
74SymbolTable::SymbolTable()
[e67991f]75: idTable(), typeTable(), structTable(), enumTable(), unionTable(), traitTable(),
[d76c588]76  prevScope(), scope( 0 ), repScope( 0 ) { ++*stats().count; }
77
78SymbolTable::~SymbolTable() { stats().size->push( idTable ? idTable->size() : 0 ); }
79
80void SymbolTable::enterScope() {
81        ++scope;
82
83        ++*stats().new_scopes;
84        stats().avg_scope_depth->push( scope );
85        stats().max_scope_depth->push( scope );
86}
87
88void SymbolTable::leaveScope() {
89        if ( repScope == scope ) {
90                Ptr prev = prevScope;           // make sure prevScope stays live
91                *this = std::move(*prevScope);  // replace with previous scope
92        }
93
94        --scope;
95}
96
[e5c3811]97SymbolTable::SpecialFunctionKind SymbolTable::getSpecialFunctionKind(const std::string & name) {
98        if (name == "?{}") return CTOR;
99        if (name == "^?{}") return DTOR;
100        if (name == "?=?") return ASSIGN;
101        return NUMBER_OF_KINDS;
102}
103
[d76c588]104std::vector<SymbolTable::IdData> SymbolTable::lookupId( const std::string &id ) const {
[e5c3811]105        static Stats::Counters::CounterGroup * name_lookup_stats = Stats::Counters::build<Stats::Counters::CounterGroup>("Name Lookup Stats");
106        static std::map<std::string, Stats::Counters::SimpleCounter *> lookups_by_name;
107        static std::map<std::string, Stats::Counters::SimpleCounter *> candidates_by_name;
108
109        SpecialFunctionKind kind = getSpecialFunctionKind(id);
110        if (kind != NUMBER_OF_KINDS) return specialLookupId(kind);
111
[d76c588]112        ++*stats().lookup_calls;
113        if ( ! idTable ) return {};
114
115        ++*stats().map_lookups;
116        auto decls = idTable->find( id );
117        if ( decls == idTable->end() ) return {};
118
119        std::vector<IdData> out;
120        for ( auto decl : *(decls->second) ) {
121                out.push_back( decl.second );
122        }
[e5c3811]123
124        if (Stats::Counters::enabled) {
125                if (! lookups_by_name.count(id)) {
126                        // leaks some strings, but it is because Counters do not hold them
127                        auto lookupCounterName = new std::string(id + "%count");
128                        auto candidatesCounterName = new std::string(id + "%candidate");
129                        lookups_by_name.emplace(id, new Stats::Counters::SimpleCounter(lookupCounterName->c_str(), name_lookup_stats));
130                        candidates_by_name.emplace(id, new Stats::Counters::SimpleCounter(candidatesCounterName->c_str(), name_lookup_stats));
131                }
132                (*lookups_by_name[id]) ++;
133                *candidates_by_name[id] += out.size();
134        }
135
136        return out;
137}
138
139std::vector<SymbolTable::IdData> SymbolTable::specialLookupId( SymbolTable::SpecialFunctionKind kind, const std::string & otypeKey ) const {
140        static Stats::Counters::CounterGroup * special_stats = Stats::Counters::build<Stats::Counters::CounterGroup>("Special Lookups");
141        static Stats::Counters::SimpleCounter * stat_counts[3] = {
142                Stats::Counters::build<Stats::Counters::SimpleCounter>("constructor - count", special_stats),
143                Stats::Counters::build<Stats::Counters::SimpleCounter>("destructor - count", special_stats),
144                Stats::Counters::build<Stats::Counters::SimpleCounter>("assignment - count", special_stats)
145        };
146
147        static Stats::Counters::SimpleCounter * stat_candidates[3] = {
148                Stats::Counters::build<Stats::Counters::SimpleCounter>("constructor - candidates", special_stats),
149                Stats::Counters::build<Stats::Counters::SimpleCounter>("destructor - candidates", special_stats),
150                Stats::Counters::build<Stats::Counters::SimpleCounter>("assignment - candidates", special_stats)
151        };
152
153        static Stats::Counters::SimpleCounter * num_lookup_with_key
154                = Stats::Counters::build<Stats::Counters::SimpleCounter>("keyed lookups", special_stats);
155        static Stats::Counters::SimpleCounter * num_lookup_without_key
156                = Stats::Counters::build<Stats::Counters::SimpleCounter>("unkeyed lookups", special_stats);
157
158        assert (kind != NUMBER_OF_KINDS);
159        ++*stats().lookup_calls;
160        if ( ! specialFunctionTable[kind] ) return {};
161
162        std::vector<IdData> out;
163
164        if (otypeKey.empty()) { // returns everything
165                ++*num_lookup_without_key;
166                for (auto & table : *specialFunctionTable[kind]) {
167                        for (auto & decl : *table.second) {
168                                out.push_back(decl.second);
169                        }
170                }
171        }
172        else {
173                ++*num_lookup_with_key;
174                ++*stats().map_lookups;
175                auto decls = specialFunctionTable[kind]->find(otypeKey);
176                if (decls == specialFunctionTable[kind]->end()) return {};
177
178                for (auto decl : *(decls->second)) {
179                        out.push_back(decl.second);
180                }
181        }
182
183        ++*stat_counts[kind];
184        *stat_candidates[kind] += out.size();
185
[d76c588]186        return out;
187}
188
189const NamedTypeDecl * SymbolTable::lookupType( const std::string &id ) const {
190        ++*stats().lookup_calls;
191        if ( ! typeTable ) return nullptr;
192        ++*stats().map_lookups;
193        auto it = typeTable->find( id );
194        return it == typeTable->end() ? nullptr : it->second.decl;
195}
196
197const StructDecl * SymbolTable::lookupStruct( const std::string &id ) const {
198        ++*stats().lookup_calls;
199        if ( ! structTable ) return nullptr;
200        ++*stats().map_lookups;
201        auto it = structTable->find( id );
202        return it == structTable->end() ? nullptr : it->second.decl;
203}
204
205const EnumDecl * SymbolTable::lookupEnum( const std::string &id ) const {
206        ++*stats().lookup_calls;
207        if ( ! enumTable ) return nullptr;
208        ++*stats().map_lookups;
209        auto it = enumTable->find( id );
210        return it == enumTable->end() ? nullptr : it->second.decl;
211}
212
213const UnionDecl * SymbolTable::lookupUnion( const std::string &id ) const {
214        ++*stats().lookup_calls;
215        if ( ! unionTable ) return nullptr;
216        ++*stats().map_lookups;
217        auto it = unionTable->find( id );
218        return it == unionTable->end() ? nullptr : it->second.decl;
219}
220
221const TraitDecl * SymbolTable::lookupTrait( const std::string &id ) const {
222        ++*stats().lookup_calls;
223        if ( ! traitTable ) return nullptr;
224        ++*stats().map_lookups;
225        auto it = traitTable->find( id );
226        return it == traitTable->end() ? nullptr : it->second.decl;
227}
228
229const NamedTypeDecl * SymbolTable::globalLookupType( const std::string &id ) const {
230        return atScope( 0 )->lookupType( id );
231}
232
233const StructDecl * SymbolTable::globalLookupStruct( const std::string &id ) const {
234        return atScope( 0 )->lookupStruct( id );
235}
236
237const UnionDecl * SymbolTable::globalLookupUnion( const std::string &id ) const {
238        return atScope( 0 )->lookupUnion( id );
239}
240
241const EnumDecl * SymbolTable::globalLookupEnum( const std::string &id ) const {
242        return atScope( 0 )->lookupEnum( id );
243}
244
245void SymbolTable::addId( const DeclWithType * decl, const Expr * baseExpr ) {
246        // default handling of conflicts is to raise an error
247        addId( decl, OnConflict::error(), baseExpr, decl->isDeleted ? decl : nullptr );
248}
249
[e67991f]250void SymbolTable::addDeletedId( const DeclWithType * decl, const Decl * deleter ) {
[d76c588]251        // default handling of conflicts is to raise an error
252        addId( decl, OnConflict::error(), nullptr, deleter );
253}
254
255namespace {
256        /// true if redeclaration conflict between two types
257        bool addedTypeConflicts( const NamedTypeDecl * existing, const NamedTypeDecl * added ) {
258                if ( existing->base == nullptr ) {
259                        return false;
260                } else if ( added->base == nullptr ) {
261                        return true;
262                } else {
263                        // typedef redeclarations are errors only if types are different
264                        if ( ! ResolvExpr::typesCompatible( existing->base, added->base, SymbolTable{} ) ) {
265                                SemanticError( added->location, "redeclaration of " + added->name );
266                        }
267                }
[e67991f]268                // does not need to be added to the table if both existing and added have a base that are
[d76c588]269                // the same
270                return true;
271        }
272
273        /// true if redeclaration conflict between two aggregate declarations
274        bool addedDeclConflicts( const AggregateDecl * existing, const AggregateDecl * added ) {
275                if ( ! existing->body ) {
276                        return false;
277                } else if ( added->body ) {
278                        SemanticError( added, "redeclaration of " );
279                }
280                return true;
281        }
282}
283
284void SymbolTable::addType( const NamedTypeDecl * decl ) {
285        ++*stats().add_calls;
286        const std::string &id = decl->name;
287
[e67991f]288        if ( ! typeTable ) {
[d76c588]289                typeTable = TypeTable::new_ptr();
290        } else {
291                ++*stats().map_lookups;
292                auto existing = typeTable->find( id );
[e67991f]293                if ( existing != typeTable->end()
294                        && existing->second.scope == scope
[d76c588]295                        && addedTypeConflicts( existing->second.decl, decl ) ) return;
296        }
[e67991f]297
[d76c588]298        lazyInitScope();
299        ++*stats().map_mutations;
300        typeTable = typeTable->set( id, scoped<NamedTypeDecl>{ decl, scope } );
301}
302
303void SymbolTable::addStruct( const std::string &id ) {
304        addStruct( new StructDecl( CodeLocation{}, id ) );
305}
306
307void SymbolTable::addStruct( const StructDecl * decl ) {
308        ++*stats().add_calls;
309        const std::string &id = decl->name;
310
311        if ( ! structTable ) {
312                structTable = StructTable::new_ptr();
313        } else {
314                ++*stats().map_lookups;
315                auto existing = structTable->find( id );
[e67991f]316                if ( existing != structTable->end()
317                        && existing->second.scope == scope
[d76c588]318                        && addedDeclConflicts( existing->second.decl, decl ) ) return;
319        }
320
321        lazyInitScope();
322        ++*stats().map_mutations;
323        structTable = structTable->set( id, scoped<StructDecl>{ decl, scope } );
324}
325
326void SymbolTable::addEnum( const EnumDecl *decl ) {
327        ++*stats().add_calls;
328        const std::string &id = decl->name;
329
330        if ( ! enumTable ) {
331                enumTable = EnumTable::new_ptr();
332        } else {
333                ++*stats().map_lookups;
334                auto existing = enumTable->find( id );
[e67991f]335                if ( existing != enumTable->end()
336                        && existing->second.scope == scope
[d76c588]337                        && addedDeclConflicts( existing->second.decl, decl ) ) return;
338        }
[e67991f]339
[d76c588]340        lazyInitScope();
341        ++*stats().map_mutations;
342        enumTable = enumTable->set( id, scoped<EnumDecl>{ decl, scope } );
343}
344
345void SymbolTable::addUnion( const std::string &id ) {
346        addUnion( new UnionDecl( CodeLocation{}, id ) );
347}
348
349void SymbolTable::addUnion( const UnionDecl * decl ) {
350        ++*stats().add_calls;
351        const std::string &id = decl->name;
352
353        if ( ! unionTable ) {
354                unionTable = UnionTable::new_ptr();
355        } else {
356                ++*stats().map_lookups;
357                auto existing = unionTable->find( id );
[e67991f]358                if ( existing != unionTable->end()
359                        && existing->second.scope == scope
[d76c588]360                        && addedDeclConflicts( existing->second.decl, decl ) ) return;
361        }
362
363        lazyInitScope();
364        ++*stats().map_mutations;
365        unionTable = unionTable->set( id, scoped<UnionDecl>{ decl, scope } );
366}
367
368void SymbolTable::addTrait( const TraitDecl * decl ) {
369        ++*stats().add_calls;
370        const std::string &id = decl->name;
371
372        if ( ! traitTable ) {
373                traitTable = TraitTable::new_ptr();
374        } else {
375                ++*stats().map_lookups;
376                auto existing = traitTable->find( id );
[e67991f]377                if ( existing != traitTable->end()
378                        && existing->second.scope == scope
[d76c588]379                        && addedDeclConflicts( existing->second.decl, decl ) ) return;
380        }
381
382        lazyInitScope();
383        ++*stats().map_mutations;
384        traitTable = traitTable->set( id, scoped<TraitDecl>{ decl, scope } );
385}
386
387
[e67991f]388void SymbolTable::addWith( const std::vector< ptr<Expr> > & withExprs, const Decl * withStmt ) {
[d76c588]389        for ( const Expr * expr : withExprs ) {
390                if ( ! expr->result ) continue;
391                const Type * resTy = expr->result->stripReferences();
[98e8b3b]392                auto aggrType = dynamic_cast< const BaseInstType * >( resTy );
[e67991f]393                assertf( aggrType, "WithStmt expr has non-aggregate type: %s",
[d76c588]394                        toString( expr->result ).c_str() );
395                const AggregateDecl * aggr = aggrType->aggr();
[e67991f]396                assertf( aggr, "WithStmt has null aggregate from type: %s",
[d76c588]397                        toString( expr->result ).c_str() );
[e67991f]398
[d76c588]399                addMembers( aggr, expr, OnConflict::deleteWith( withStmt ) );
400        }
401}
402
403void SymbolTable::addIds( const std::vector< ptr<DeclWithType> > & decls ) {
404        for ( const DeclWithType * decl : decls ) { addId( decl ); }
405}
406
407void SymbolTable::addTypes( const std::vector< ptr<TypeDecl> > & tds ) {
408        for ( const TypeDecl * td : tds ) {
409                addType( td );
410                addIds( td->assertions );
411        }
412}
413
[490fb92e]414
415void SymbolTable::addFunction( const FunctionDecl * func ) {
[3e5dd913]416        for (auto & td : func->type_params) {
417                addType(td);
418        }
419        for (auto & asst : func->assertions) {
420                addId(asst);
421        }
422        // addTypes( func->type->forall );
[490fb92e]423        addIds( func->returns );
424        addIds( func->params );
[d76c588]425}
[490fb92e]426
[d76c588]427
428void SymbolTable::lazyInitScope() {
429        // do nothing if already in represented scope
430        if ( repScope == scope ) return;
431
432        ++*stats().lazy_scopes;
433        // create rollback
434        prevScope = std::make_shared<SymbolTable>( *this );
435        // update repScope
436        repScope = scope;
437}
438
439const ast::SymbolTable * SymbolTable::atScope( unsigned long target ) const {
440        // by lazy construction, final symtab in list has repScope 0, cannot be > target
441        // otherwise, will find first scope representing the target
442        const SymbolTable * symtab = this;
443        while ( symtab->repScope > target ) {
444                symtab = symtab->prevScope.get();
445        }
446        return symtab;
447}
448
449namespace {
450        /// gets the base type of the first parameter; decl must be a ctor/dtor/assignment function
[e5c3811]451        std::string getOtypeKey( const FunctionType * ftype, bool stripParams = true ) {
452                const auto & params = ftype->params;
[d76c588]453                assert( ! params.empty() );
454                // use base type of pointer, so that qualifiers on the pointer type aren't considered.
[954c954]455                const Type * base = InitTweak::getPointerBase( params.front() );
[d76c588]456                assert( base );
[e5c3811]457                if (stripParams) {
458                        if (dynamic_cast<const PointerType *>(base)) return Mangle::Encoding::pointer;
459                        return Mangle::mangle( base, Mangle::Type | Mangle::NoGenericParams );
460                }
461                else
462                        return Mangle::mangle( base ); 
[d76c588]463        }
464
[e67991f]465        /// gets the declaration for the function acting on a type specified by otype key,
[d76c588]466        /// nullptr if none such
[e67991f]467        const FunctionDecl * getFunctionForOtype(
[d76c588]468                        const DeclWithType * decl, const std::string & otypeKey ) {
469                auto func = dynamic_cast< const FunctionDecl * >( decl );
[e5c3811]470                if ( ! func || otypeKey != getOtypeKey( func->type, false ) ) return nullptr;
[d76c588]471                return func;
472        }
473}
474
[e67991f]475bool SymbolTable::removeSpecialOverrides(
[d76c588]476                SymbolTable::IdData & data, SymbolTable::MangleTable::Ptr & mangleTable ) {
[e67991f]477        // if a type contains user defined ctor/dtor/assign, then special rules trigger, which
478        // determine the set of ctor/dtor/assign that can be used  by the requester. In particular,
479        // if the user defines a default ctor, then the generated default ctor is unavailable,
480        // likewise for copy ctor and dtor. If the user defines any ctor/dtor, then no generated
481        // field ctors are available. If the user defines any ctor then the generated default ctor
482        // is unavailable (intrinsic default ctor must be overridden exactly). If the user defines
483        // anything that looks like a copy constructor, then the generated copy constructor is
[d76c588]484        // unavailable, and likewise for the assignment operator.
485
486        // only relevant on function declarations
487        const FunctionDecl * function = data.id.as< FunctionDecl >();
488        if ( ! function ) return true;
489        // only need to perform this check for constructors, destructors, and assignment functions
490        if ( ! CodeGen::isCtorDtorAssign( data.id->name ) ) return true;
491
492        // set up information for this type
493        bool dataIsUserDefinedFunc = ! function->linkage.is_overrideable;
494        bool dataIsCopyFunc = InitTweak::isCopyFunction( function );
[e5c3811]495        std::string dataOtypeKey = getOtypeKey( function->type, false ); // requires exact match to override autogen
[d76c588]496
497        if ( dataIsUserDefinedFunc && dataIsCopyFunc ) {
498                // this is a user-defined copy function
499                // if this is the first such, delete/remove non-user-defined overloads as needed
500                std::vector< std::string > removed;
501                std::vector< MangleTable::value_type > deleted;
502                bool alreadyUserDefinedFunc = false;
503
504                for ( const auto& entry : *mangleTable ) {
505                        // skip decls that aren't functions or are for the wrong type
506                        const FunctionDecl * decl = getFunctionForOtype( entry.second.id, dataOtypeKey );
507                        if ( ! decl ) continue;
508
509                        bool isCopyFunc = InitTweak::isCopyFunction( decl );
510                        if ( ! decl->linkage.is_overrideable ) {
511                                // matching user-defined function
512                                if ( isCopyFunc ) {
513                                        // mutation already performed, return early
514                                        return true;
515                                } else {
516                                        // note that non-copy deletions already performed
517                                        alreadyUserDefinedFunc = true;
518                                }
519                        } else {
520                                // non-user-defined function; mark for deletion/removal as appropriate
521                                if ( isCopyFunc ) {
522                                        removed.push_back( entry.first );
523                                } else if ( ! alreadyUserDefinedFunc ) {
524                                        deleted.push_back( entry );
525                                }
526                        }
527                }
528
529                // perform removals from mangle table, and deletions if necessary
530                for ( const auto& key : removed ) {
531                        ++*stats().map_mutations;
532                        mangleTable = mangleTable->erase( key );
533                }
534                if ( ! alreadyUserDefinedFunc ) for ( const auto& entry : deleted ) {
535                        ++*stats().map_mutations;
536                        mangleTable = mangleTable->set( entry.first, IdData{ entry.second, function } );
537                }
538        } else if ( dataIsUserDefinedFunc ) {
539                // this is a user-defined non-copy function
540                // if this is the first user-defined function, delete non-user-defined overloads
541                std::vector< MangleTable::value_type > deleted;
[e67991f]542
[d76c588]543                for ( const auto& entry : *mangleTable ) {
544                        // skip decls that aren't functions or are for the wrong type
545                        const FunctionDecl * decl = getFunctionForOtype( entry.second.id, dataOtypeKey );
546                        if ( ! decl ) continue;
547
548                        // exit early if already a matching user-defined function;
549                        // earlier function will have mutated table
550                        if ( ! decl->linkage.is_overrideable ) return true;
551
552                        // skip mutating intrinsic functions
553                        if ( decl->linkage == Linkage::Intrinsic ) continue;
554
555                        // user-defined non-copy functions do not override copy functions
556                        if ( InitTweak::isCopyFunction( decl ) ) continue;
557
558                        // this function to be deleted after mangleTable iteration is complete
559                        deleted.push_back( entry );
560                }
561
562                // mark deletions to update mangle table
563                // this needs to be a separate loop because of iterator invalidation
564                for ( const auto& entry : deleted ) {
565                        ++*stats().map_mutations;
566                        mangleTable = mangleTable->set( entry.first, IdData{ entry.second, function } );
567                }
568        } else if ( function->linkage != Linkage::Intrinsic ) {
569                // this is an overridable generated function
570                // if there already exists a matching user-defined function, delete this appropriately
571                for ( const auto& entry : *mangleTable ) {
572                        // skip decls that aren't functions or are for the wrong type
573                        const FunctionDecl * decl = getFunctionForOtype( entry.second.id, dataOtypeKey );
574                        if ( ! decl ) continue;
575
576                        // skip non-user-defined functions
577                        if ( decl->linkage.is_overrideable ) continue;
578
579                        if ( dataIsCopyFunc ) {
580                                // remove current function if exists a user-defined copy function
[e67991f]581                                // since the signatures for copy functions don't need to match exactly, using
[d76c588]582                                // a delete statement is the wrong approach
583                                if ( InitTweak::isCopyFunction( decl ) ) return false;
584                        } else {
585                                // mark current function deleted by first user-defined function found
586                                data.deleter = decl;
587                                return true;
588                        }
589                }
590        }
[e67991f]591
[d76c588]592        // nothing (more) to fix, return true
593        return true;
594}
595
596namespace {
597        /// true iff the declaration represents a function
598        bool isFunction( const DeclWithType * decl ) {
599                return GenPoly::getFunctionType( decl->get_type() );
600        }
601
602        bool isObject( const DeclWithType * decl ) { return ! isFunction( decl ); }
603
604        /// true if the declaration represents a definition instead of a forward decl
605        bool isDefinition( const DeclWithType * decl ) {
606                if ( auto func = dynamic_cast< const FunctionDecl * >( decl ) ) {
607                        // a function is a definition if it has a body
608                        return func->stmts;
609                } else {
610                        // an object is a definition if it is not marked extern
611                        return ! decl->storage.is_extern;
612                }
613        }
614}
615
616bool SymbolTable::addedIdConflicts(
[e67991f]617                const SymbolTable::IdData & existing, const DeclWithType * added,
618                SymbolTable::OnConflict handleConflicts, const Decl * deleter ) {
619        // if we're giving the same name mangling to things of different types then there is something
[d76c588]620        // wrong
621        assert( (isObject( added ) && isObject( existing.id ) )
622                || ( isFunction( added ) && isFunction( existing.id ) ) );
[e67991f]623
[d76c588]624        if ( existing.id->linkage.is_overrideable ) {
625                // new definition shadows the autogenerated one, even at the same scope
626                return false;
[e67991f]627        } else if ( existing.id->linkage.is_mangled
628                        || ResolvExpr::typesCompatible(
[d76c588]629                                added->get_type(), existing.id->get_type(), SymbolTable{} ) ) {
[e67991f]630
[d76c588]631                // it is a conflict if one declaration is deleted and the other is not
632                if ( deleter && ! existing.deleter ) {
633                        if ( handleConflicts.mode == OnConflict::Error ) {
634                                SemanticError( added, "deletion of defined identifier " );
635                        }
636                        return true;
637                } else if ( ! deleter && existing.deleter ) {
638                        if ( handleConflicts.mode == OnConflict::Error ) {
639                                SemanticError( added, "definition of deleted identifier " );
640                        }
641                        return true;
642                }
643
644                // it is a conflict if both declarations are definitions
645                if ( isDefinition( added ) && isDefinition( existing.id ) ) {
646                        if ( handleConflicts.mode == OnConflict::Error ) {
[e67991f]647                                SemanticError( added,
648                                        isFunction( added ) ?
649                                                "duplicate function definition for " :
[d76c588]650                                                "duplicate object definition for " );
651                        }
652                        return true;
653                }
654        } else {
655                if ( handleConflicts.mode == OnConflict::Error ) {
656                        SemanticError( added, "duplicate definition for " );
657                }
658                return true;
659        }
660
661        return true;
662}
663
[e67991f]664void SymbolTable::addId(
665                const DeclWithType * decl, SymbolTable::OnConflict handleConflicts, const Expr * baseExpr,
666                const Decl * deleter ) {
[e5c3811]667        SpecialFunctionKind kind = getSpecialFunctionKind(decl->name);
668        if (kind == NUMBER_OF_KINDS) { // not a special decl
669                addId(decl, decl->name, idTable, handleConflicts, baseExpr, deleter);
670        }
671        else {
672                std::string key;
673                if (auto func = dynamic_cast<const FunctionDecl *>(decl)) {
674                        key = getOtypeKey(func->type);
675                }
676                else if (auto obj = dynamic_cast<const ObjectDecl *>(decl)) {
677                        key = getOtypeKey(obj->type.strict_as<PointerType>()->base.strict_as<FunctionType>());
678                }
679                else {
680                        assertf(false, "special decl with non-function type");
681                }
682                addId(decl, key, specialFunctionTable[kind], handleConflicts, baseExpr, deleter);
683        }
684}
685
686void SymbolTable::addId(
687                const DeclWithType * decl, const std::string & lookupKey, IdTable::Ptr & table, SymbolTable::OnConflict handleConflicts, const Expr * baseExpr,
688                const Decl * deleter ) {
[d76c588]689        ++*stats().add_calls;
690        const std::string &name = decl->name;
691        if ( name == "" ) return;
692
693        std::string mangleName;
694        if ( decl->linkage.is_overrideable ) {
[e67991f]695                // mangle the name without including the appropriate suffix, so overridable routines
[d76c588]696                // are placed into the same "bucket" as their user defined versions.
697                mangleName = Mangle::mangle( decl, Mangle::Mode{ Mangle::NoOverrideable } );
698        } else {
699                mangleName = Mangle::mangle( decl );
700        }
701
[e67991f]702        // this ensures that no two declarations with the same unmangled name at the same scope
[d76c588]703        // both have C linkage
704        if ( decl->linkage.is_mangled ) {
705                // Check that a Cforall declaration doesn't override any C declaration
706                if ( hasCompatibleCDecl( name, mangleName ) ) {
707                        SemanticError( decl, "Cforall declaration hides C function " );
708                }
709        } else {
[e67991f]710                // NOTE: only correct if name mangling is completely isomorphic to C
[d76c588]711                // type-compatibility, which it may not be.
712                if ( hasIncompatibleCDecl( name, mangleName ) ) {
713                        SemanticError( decl, "conflicting overload of C function " );
714                }
715        }
716
717        // ensure tables exist and add identifier
718        MangleTable::Ptr mangleTable;
[e5c3811]719        if ( ! table ) {
720                table = IdTable::new_ptr();
[d76c588]721                mangleTable = MangleTable::new_ptr();
722        } else {
723                ++*stats().map_lookups;
[e5c3811]724                auto decls = table->find( lookupKey );
725                if ( decls == table->end() ) {
[d76c588]726                        mangleTable = MangleTable::new_ptr();
727                } else {
728                        mangleTable = decls->second;
729                        // skip in-scope repeat declarations of same identifier
730                        ++*stats().map_lookups;
731                        auto existing = mangleTable->find( mangleName );
732                        if ( existing != mangleTable->end()
733                                        && existing->second.scope == scope
734                                        && existing->second.id ) {
735                                if ( addedIdConflicts( existing->second, decl, handleConflicts, deleter ) ) {
736                                        if ( handleConflicts.mode == OnConflict::Delete ) {
737                                                // set delete expression for conflicting identifier
738                                                lazyInitScope();
739                                                *stats().map_mutations += 2;
[e5c3811]740                                                table = table->set(
741                                                        lookupKey,
[e67991f]742                                                        mangleTable->set(
743                                                                mangleName,
[d76c588]744                                                                IdData{ existing->second, handleConflicts.deleter } ) );
745                                        }
746                                        return;
747                                }
748                        }
749                }
750        }
751
752        // add/overwrite with new identifier
753        lazyInitScope();
754        IdData data{ decl, baseExpr, deleter, scope };
755        // Ensure that auto-generated ctor/dtor/assignment are deleted if necessary
[e5c3811]756        if (table != idTable) { // adding to special table
757                if ( ! removeSpecialOverrides( data, mangleTable ) ) return;
758        }
[d76c588]759        *stats().map_mutations += 2;
[e5c3811]760        table = table->set( lookupKey, mangleTable->set( mangleName, std::move(data) ) );
[d76c588]761}
762
[e67991f]763void SymbolTable::addMembers(
[d76c588]764                const AggregateDecl * aggr, const Expr * expr, SymbolTable::OnConflict handleConflicts ) {
765        for ( const Decl * decl : aggr->members ) {
766                if ( auto dwt = dynamic_cast< const DeclWithType * >( decl ) ) {
767                        addId( dwt, handleConflicts, expr );
768                        if ( dwt->name == "" ) {
769                                const Type * t = dwt->get_type()->stripReferences();
[98e8b3b]770                                if ( auto rty = dynamic_cast<const BaseInstType *>( t ) ) {
[e67991f]771                                        if ( ! dynamic_cast<const StructInstType *>(rty)
[d76c588]772                                                && ! dynamic_cast<const UnionInstType *>(rty) ) continue;
773                                        ResolvExpr::Cost cost = ResolvExpr::Cost::zero;
774                                        const Expr * base = ResolvExpr::referenceToRvalueConversion( expr, cost );
[e67991f]775                                        addMembers(
[d76c588]776                                                rty->aggr(), new MemberExpr{ base->location, dwt, base }, handleConflicts );
777                                }
778                        }
779                }
780        }
781}
782
783bool SymbolTable::hasCompatibleCDecl( const std::string &id, const std::string &mangleName ) const {
784        if ( ! idTable ) return false;
785
786        ++*stats().map_lookups;
787        auto decls = idTable->find( id );
788        if ( decls == idTable->end() ) return false;
789
790        for ( auto decl : *(decls->second) ) {
791                // skip other scopes (hidden by this decl)
792                if ( decl.second.scope != scope ) continue;
793                // check for C decl with compatible type (by mangleName)
794                if ( ! decl.second.id->linkage.is_mangled && decl.first == mangleName ) return true;
795        }
[e67991f]796
[d76c588]797        return false;
798}
799
800bool SymbolTable::hasIncompatibleCDecl( const std::string &id, const std::string &mangleName ) const {
801        if ( ! idTable ) return false;
802
803        ++*stats().map_lookups;
804        auto decls = idTable->find( id );
805        if ( decls == idTable->end() ) return false;
806
807        for ( auto decl : *(decls->second) ) {
808                // skip other scopes (hidden by this decl)
809                if ( decl.second.scope != scope ) continue;
810                // check for C decl with incompatible type (by manglename)
811                if ( ! decl.second.id->linkage.is_mangled && decl.first != mangleName ) return true;
812        }
813
814        return false;
815}
816
817}
818
819// Local Variables: //
820// tab-width: 4 //
821// mode: c++ //
822// compile-command: "make install" //
[98e8b3b]823// End: //
Note: See TracBrowser for help on using the repository browser.