source: src/ResolvExpr/Resolver.cc @ bbbc067

no_list
Last change on this file since bbbc067 was bbbc067, checked in by Thierry Delisle <tdelisle@…>, 5 years ago

Changed std::list<Initializer> to vector

  • Property mode set to 100644
File size: 34.3 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// Resolver.cc --
8//
9// Author           : Richard C. Bilson
10// Created On       : Sun May 17 12:17:01 2015
11// Last Modified By : Aaron B. Moss
12// Last Modified On : Fri Oct 05 09:43:00 2018
13// Update Count     : 214
14//
15
16#include <cassert>                       // for strict_dynamic_cast, assert
17#include <memory>                        // for allocator, allocator_traits<...
18#include <tuple>                         // for get
19#include <vector>                        // for vector
20
21#include "Alternative.h"                 // for Alternative, AltList
22#include "AlternativeFinder.h"           // for AlternativeFinder, resolveIn...
23#include "Common/PassVisitor.h"          // for PassVisitor
24#include "Common/SemanticError.h"        // for SemanticError
25#include "Common/utility.h"              // for ValueGuard, group_iterate
26#include "CurrentObject.h"               // for CurrentObject
27#include "InitTweak/GenInit.h"
28#include "InitTweak/InitTweak.h"         // for isIntrinsicSingleArgCallStmt
29#include "RenameVars.h"                  // for RenameVars, global_renamer
30#include "ResolvExpr/TypeEnvironment.h"  // for TypeEnvironment
31#include "Resolver.h"
32#include "ResolvMode.h"                  // for ResolvMode
33#include "SymTab/Autogen.h"              // for SizeType
34#include "SymTab/Indexer.h"              // for Indexer
35#include "SynTree/Declaration.h"         // for ObjectDecl, TypeDecl, Declar...
36#include "SynTree/Expression.h"          // for Expression, CastExpr, InitExpr
37#include "SynTree/Initializer.h"         // for ConstructorInit, SingleInit
38#include "SynTree/Statement.h"           // for ForStmt, Statement, BranchStmt
39#include "SynTree/Type.h"                // for Type, BasicType, PointerType
40#include "SynTree/TypeSubstitution.h"    // for TypeSubstitution
41#include "SynTree/Visitor.h"             // for acceptAll, maybeAccept
42#include "Tuples/Tuples.h"
43#include "typeops.h"                     // for extractResultType
44#include "Unify.h"                       // for unify
45
46using namespace std;
47
48namespace ResolvExpr {
49        struct Resolver final : public WithIndexer, public WithGuards, public WithVisitorRef<Resolver>, public WithShortCircuiting, public WithStmtsToAdd {
50                Resolver() {}
51                Resolver( const SymTab::Indexer & other ) {
52                        indexer = other;
53                }
54
55                void previsit( FunctionDecl *functionDecl );
56                void postvisit( FunctionDecl *functionDecl );
57                void previsit( ObjectDecl *objectDecll );
58                void previsit( EnumDecl * enumDecl );
59                void previsit( StaticAssertDecl * assertDecl );
60
61                void previsit( ArrayType * at );
62                void previsit( PointerType * at );
63
64                void previsit( ExprStmt *exprStmt );
65                void previsit( AsmExpr *asmExpr );
66                void previsit( AsmStmt *asmStmt );
67                void previsit( IfStmt *ifStmt );
68                void previsit( WhileStmt *whileStmt );
69                void previsit( ForStmt *forStmt );
70                void previsit( SwitchStmt *switchStmt );
71                void previsit( CaseStmt *caseStmt );
72                void previsit( BranchStmt *branchStmt );
73                void previsit( ReturnStmt *returnStmt );
74                void previsit( ThrowStmt *throwStmt );
75                void previsit( CatchStmt *catchStmt );
76                void previsit( WaitForStmt * stmt );
77
78                void previsit( SingleInit *singleInit );
79                void previsit( ListInit *listInit );
80                void previsit( ConstructorInit *ctorInit );
81          private:
82                typedef std::vector< Initializer * >::iterator InitIterator;
83
84                template< typename PtrType >
85                void handlePtrType( PtrType * type );
86
87                void fallbackInit( ConstructorInit * ctorInit );
88
89                Type * functionReturn = nullptr;
90                CurrentObject currentObject = nullptr;
91                bool inEnumDecl = false;
92        };
93
94        struct ResolveWithExprs : public WithIndexer, public WithGuards, public WithVisitorRef<ResolveWithExprs>, public WithShortCircuiting, public WithStmtsToAdd {
95                void previsit( FunctionDecl * );
96                void previsit( WithStmt * );
97
98                void resolveWithExprs( std::list< Expression * > & withExprs, std::list< Statement * > & newStmts );
99        };
100
101        void resolve( std::list< Declaration * > translationUnit ) {
102                PassVisitor<Resolver> resolver;
103                acceptAll( translationUnit, resolver );
104        }
105
106        void resolveDecl( Declaration * decl, const SymTab::Indexer &indexer ) {
107                PassVisitor<Resolver> resolver( indexer );
108                maybeAccept( decl, resolver );
109        }
110
111        namespace {
112                struct DeleteFinder : public WithShortCircuiting        {
113                        DeletedExpr * delExpr = nullptr;
114                        void previsit( DeletedExpr * expr ) {
115                                if ( delExpr ) visit_children = false;
116                                else delExpr = expr;
117                        }
118
119                        void previsit( Expression * ) {
120                                if ( delExpr ) visit_children = false;
121                        }
122                };
123        }
124
125        DeletedExpr * findDeletedExpr( Expression * expr ) {
126                PassVisitor<DeleteFinder> finder;
127                expr->accept( finder );
128                return finder.pass.delExpr;
129        }
130
131        namespace {
132                struct StripCasts {
133                        Expression * postmutate( CastExpr * castExpr ) {
134                                if ( castExpr->isGenerated && ResolvExpr::typesCompatible( castExpr->arg->result, castExpr->result, SymTab::Indexer() ) ) {
135                                        // generated cast is to the same type as its argument, so it's unnecessary -- remove it
136                                        Expression * expr = castExpr->arg;
137                                        castExpr->arg = nullptr;
138                                        std::swap( expr->env, castExpr->env );
139                                        return expr;
140                                }
141                                return castExpr;
142                        }
143
144                        static void strip( Expression *& expr ) {
145                                PassVisitor<StripCasts> stripper;
146                                expr = expr->acceptMutator( stripper );
147                        }
148                };
149
150                void finishExpr( Expression *&expr, const TypeEnvironment &env, TypeSubstitution * oldenv = nullptr ) {
151                        expr->env = oldenv ? oldenv->clone() : new TypeSubstitution;
152                        env.makeSubstitution( *expr->env );
153                        StripCasts::strip( expr ); // remove unnecessary casts that may be buried in an expression
154                }
155
156                void removeExtraneousCast( Expression *& expr, const SymTab::Indexer & indexer ) {
157                        if ( CastExpr * castExpr = dynamic_cast< CastExpr * >( expr ) ) {
158                                if ( ResolvExpr::typesCompatible( castExpr->arg->result, castExpr->result, indexer ) ) {
159                                        // cast is to the same type as its argument, so it's unnecessary -- remove it
160                                        expr = castExpr->arg;
161                                        castExpr->arg = nullptr;
162                                        std::swap( expr->env, castExpr->env );
163                                        delete castExpr;
164                                }
165                        }
166                }
167        } // namespace
168
169        namespace {
170                void findUnfinishedKindExpression(Expression * untyped, Alternative & alt, const SymTab::Indexer & indexer, const std::string & kindStr, std::function<bool(const Alternative &)> pred, ResolvMode mode = ResolvMode{} ) {
171                        assertf( untyped, "expected a non-null expression." );
172
173                        // xxx - this isn't thread-safe, but should work until we parallelize the resolver
174                        static unsigned recursion_level = 0;
175
176                        ++recursion_level;
177                        TypeEnvironment env;
178                        AlternativeFinder finder( indexer, env );
179                        finder.find( untyped, recursion_level == 1 ? mode.atTopLevel() : mode );
180                        --recursion_level;
181
182                        #if 0
183                        if ( finder.get_alternatives().size() != 1 ) {
184                                std::cerr << "untyped expr is ";
185                                untyped->print( std::cerr );
186                                std::cerr << std::endl << "alternatives are:";
187                                for ( const Alternative & alt : finder.get_alternatives() ) {
188                                        alt.print( std::cerr );
189                                } // for
190                        } // if
191                        #endif
192
193                        // produce filtered list of alternatives
194                        AltList candidates;
195                        for ( Alternative & alt : finder.get_alternatives() ) {
196                                if ( pred( alt ) ) {
197                                        candidates.push_back( std::move( alt ) );
198                                }
199                        }
200
201                        // produce invalid error if no candidates
202                        if ( candidates.empty() ) {
203                                SemanticError( untyped, toString( "No reasonable alternatives for ", kindStr, (kindStr != "" ? " " : ""), "expression: ") );
204                        }
205
206                        // search for cheapest candidate
207                        AltList winners;
208                        bool seen_undeleted = false;
209                        for ( unsigned i = 0; i < candidates.size(); ++i ) {
210                                int c = winners.empty() ? -1 : candidates[i].cost.compare( winners.front().cost );
211
212                                if ( c > 0 ) continue; // skip more expensive than winner
213
214                                if ( c < 0 ) {
215                                        // reset on new cheapest
216                                        seen_undeleted = ! findDeletedExpr( candidates[i].expr );
217                                        winners.clear();
218                                } else /* if ( c == 0 ) */ {
219                                        if ( findDeletedExpr( candidates[i].expr ) ) {
220                                                // skip deleted expression if already seen one equivalent-cost not
221                                                if ( seen_undeleted ) continue;
222                                        } else if ( ! seen_undeleted ) {
223                                                // replace list of equivalent-cost deleted expressions with one non-deleted
224                                                winners.clear();
225                                                seen_undeleted = true;
226                                        }
227                                }
228
229                                winners.emplace_back( std::move( candidates[i] ) );
230                        }
231
232                        // promote alternative.cvtCost to .cost
233                        // xxx - I don't know why this is done, but I'm keeping the behaviour from findMinCost
234                        for ( Alternative& winner : winners ) {
235                                winner.cost = winner.cvtCost;
236                        }
237
238                        // produce ambiguous errors, if applicable
239                        if ( winners.size() != 1 ) {
240                                std::ostringstream stream;
241                                stream << "Cannot choose between " << winners.size() << " alternatives for " << kindStr << (kindStr != "" ? " " : "") << "expression\n";
242                                untyped->print( stream );
243                                stream << " Alternatives are:\n";
244                                printAlts( winners, stream, 1 );
245                                SemanticError( untyped->location, stream.str() );
246                        }
247
248                        // single selected choice
249                        Alternative& choice = winners.front();
250
251                        // fail on only expression deleted
252                        if ( ! seen_undeleted ) {
253                                SemanticError( untyped->location, choice.expr, "Unique best alternative includes deleted identifier in " );
254                        }
255
256                        // xxx - check for ambiguous expressions
257
258                        // output selected choice
259                        alt = std::move( choice );
260                }
261
262                /// resolve `untyped` to the expression whose alternative satisfies `pred` with the lowest cost; kindStr is used for providing better error messages
263                void findKindExpression(Expression *& untyped, const SymTab::Indexer & indexer, const std::string & kindStr, std::function<bool(const Alternative &)> pred, ResolvMode mode = ResolvMode{}) {
264                        if ( ! untyped ) return;
265                        Alternative choice;
266                        findUnfinishedKindExpression( untyped, choice, indexer, kindStr, pred, mode );
267                        finishExpr( choice.expr, choice.env, untyped->env );
268                        delete untyped;
269                        untyped = choice.expr;
270                        choice.expr = nullptr;
271                }
272
273                bool standardAlternativeFilter( const Alternative & ) {
274                        // currently don't need to filter, under normal circumstances.
275                        // in the future, this may be useful for removing deleted expressions
276                        return true;
277                }
278        } // namespace
279
280        // used in resolveTypeof
281        Expression * resolveInVoidContext( Expression *expr, const SymTab::Indexer &indexer ) {
282                TypeEnvironment env;
283                return resolveInVoidContext( expr, indexer, env );
284        }
285
286        Expression * resolveInVoidContext( Expression *expr, const SymTab::Indexer &indexer, TypeEnvironment &env ) {
287                // it's a property of the language that a cast expression has either 1 or 0 interpretations; if it has 0
288                // interpretations, an exception has already been thrown.
289                assertf( expr, "expected a non-null expression." );
290
291                static CastExpr untyped( nullptr ); // cast to void
292                untyped.location = expr->location;
293
294                // set up and resolve expression cast to void
295                untyped.arg = expr;
296                Alternative choice;
297                findUnfinishedKindExpression( &untyped, choice, indexer, "", standardAlternativeFilter, ResolvMode::withAdjustment() );
298                CastExpr * castExpr = strict_dynamic_cast< CastExpr * >( choice.expr );
299                env = std::move( choice.env );
300
301                // clean up resolved expression
302                Expression * ret = castExpr->arg;
303                castExpr->arg = nullptr;
304
305                // unlink the arg so that it isn't deleted twice at the end of the program
306                untyped.arg = nullptr;
307                return ret;
308        }
309
310        void findVoidExpression( Expression *& untyped, const SymTab::Indexer &indexer ) {
311                resetTyVarRenaming();
312                TypeEnvironment env;
313                Expression * newExpr = resolveInVoidContext( untyped, indexer, env );
314                finishExpr( newExpr, env, untyped->env );
315                delete untyped;
316                untyped = newExpr;
317        }
318
319        void findSingleExpression( Expression *&untyped, const SymTab::Indexer &indexer ) {
320                findKindExpression( untyped, indexer, "", standardAlternativeFilter );
321        }
322
323        void findSingleExpression( Expression *& untyped, Type * type, const SymTab::Indexer & indexer ) {
324                assert( untyped && type );
325                // transfer location to generated cast for error purposes
326                CodeLocation location = untyped->location;
327                untyped = new CastExpr( untyped, type );
328                untyped->location = location;
329                findSingleExpression( untyped, indexer );
330                removeExtraneousCast( untyped, indexer );
331        }
332
333        namespace {
334                bool isIntegralType( const Alternative & alt ) {
335                        Type * type = alt.expr->result;
336                        if ( dynamic_cast< EnumInstType * >( type ) ) {
337                                return true;
338                        } else if ( BasicType *bt = dynamic_cast< BasicType * >( type ) ) {
339                                return bt->isInteger();
340                        } else if ( dynamic_cast< ZeroType* >( type ) != nullptr || dynamic_cast< OneType* >( type ) != nullptr ) {
341                                return true;
342                        } else {
343                                return false;
344                        } // if
345                }
346
347                void findIntegralExpression( Expression *& untyped, const SymTab::Indexer &indexer ) {
348                        findKindExpression( untyped, indexer, "condition", isIntegralType );
349                }
350        }
351
352
353        bool isStructOrUnion( const Alternative & alt ) {
354                Type * t = alt.expr->result->stripReferences();
355                return dynamic_cast< StructInstType * >( t ) || dynamic_cast< UnionInstType * >( t );
356        }
357
358        void resolveWithExprs( std::list< Declaration * > & translationUnit ) {
359                PassVisitor<ResolveWithExprs> resolver;
360                acceptAll( translationUnit, resolver );
361        }
362
363        void ResolveWithExprs::resolveWithExprs( std::list< Expression * > & withExprs, std::list< Statement * > & newStmts ) {
364                for ( Expression *& expr : withExprs )  {
365                        // only struct- and union-typed expressions are viable candidates
366                        findKindExpression( expr, indexer, "with statement", isStructOrUnion );
367
368                        // if with expression might be impure, create a temporary so that it is evaluated once
369                        if ( Tuples::maybeImpure( expr ) ) {
370                                static UniqueName tmpNamer( "_with_tmp_" );
371                                ObjectDecl * tmp = ObjectDecl::newObject( tmpNamer.newName(), expr->result->clone(), new SingleInit( expr ) );
372                                expr = new VariableExpr( tmp );
373                                newStmts.push_back( new DeclStmt( tmp ) );
374                                if ( InitTweak::isConstructable( tmp->type ) ) {
375                                        // generate ctor/dtor and resolve them
376                                        tmp->init = InitTweak::genCtorInit( tmp );
377                                        tmp->accept( *visitor );
378                                }
379                        }
380                }
381        }
382
383        void ResolveWithExprs::previsit( WithStmt * withStmt ) {
384                resolveWithExprs( withStmt->exprs, stmtsToAddBefore );
385        }
386
387        void ResolveWithExprs::previsit( FunctionDecl * functionDecl ) {
388                {
389                        // resolve with-exprs with parameters in scope and add any newly generated declarations to the
390                        // front of the function body.
391                        auto guard = makeFuncGuard( [this]() { indexer.enterScope(); }, [this](){ indexer.leaveScope(); } );
392                        indexer.addFunctionType( functionDecl->type );
393                        std::list< Statement * > newStmts;
394                        resolveWithExprs( functionDecl->withExprs, newStmts );
395                        if ( functionDecl->statements ) {
396                                functionDecl->statements->kids.splice( functionDecl->statements->kids.begin(), newStmts );
397                        } else {
398                                assertf( functionDecl->withExprs.empty() && newStmts.empty(), "Function %s without a body has with-clause and/or generated with declarations.", functionDecl->name.c_str() );
399                        }
400                }
401        }
402
403        void Resolver::previsit( ObjectDecl *objectDecl ) {
404                // To handle initialization of routine pointers, e.g., int (*fp)(int) = foo(), means that
405                // class-variable initContext is changed multiple time because the LHS is analysed twice.
406                // The second analysis changes initContext because of a function type can contain object
407                // declarations in the return and parameter types. So each value of initContext is
408                // retained, so the type on the first analysis is preserved and used for selecting the RHS.
409                GuardValue( currentObject );
410                currentObject = CurrentObject( objectDecl->get_type() );
411                if ( inEnumDecl && dynamic_cast< EnumInstType * >( objectDecl->get_type() ) ) {
412                        // enumerator initializers should not use the enum type to initialize, since
413                        // the enum type is still incomplete at this point. Use signed int instead.
414                        currentObject = CurrentObject( new BasicType( Type::Qualifiers(), BasicType::SignedInt ) );
415                }
416        }
417
418        template< typename PtrType >
419        void Resolver::handlePtrType( PtrType * type ) {
420                if ( type->get_dimension() ) {
421                        findSingleExpression( type->dimension, SymTab::SizeType->clone(), indexer );
422                }
423        }
424
425        void Resolver::previsit( ArrayType * at ) {
426                handlePtrType( at );
427        }
428
429        void Resolver::previsit( PointerType * pt ) {
430                handlePtrType( pt );
431        }
432
433        void Resolver::previsit( FunctionDecl *functionDecl ) {
434#if 0
435                std::cerr << "resolver visiting functiondecl ";
436                functionDecl->print( std::cerr );
437                std::cerr << std::endl;
438#endif
439                GuardValue( functionReturn );
440                functionReturn = ResolvExpr::extractResultType( functionDecl->type );
441        }
442
443        void Resolver::postvisit( FunctionDecl *functionDecl ) {
444                // default value expressions have an environment which shouldn't be there and trips up
445                // later passes.
446                // xxx - it might be necessary to somehow keep the information from this environment, but I
447                // can't currently see how it's useful.
448                for ( Declaration * d : functionDecl->type->parameters ) {
449                        if ( ObjectDecl * obj = dynamic_cast< ObjectDecl * >( d ) ) {
450                                if ( SingleInit * init = dynamic_cast< SingleInit * >( obj->init ) ) {
451                                        delete init->value->env;
452                                        init->value->env = nullptr;
453                                }
454                        }
455                }
456        }
457
458        void Resolver::previsit( EnumDecl * ) {
459                // in case we decide to allow nested enums
460                GuardValue( inEnumDecl );
461                inEnumDecl = true;
462        }
463
464        void Resolver::previsit( StaticAssertDecl * assertDecl ) {
465                findIntegralExpression( assertDecl->condition, indexer );
466        }
467
468        void Resolver::previsit( ExprStmt *exprStmt ) {
469                visit_children = false;
470                assertf( exprStmt->expr, "ExprStmt has null Expression in resolver" );
471                findVoidExpression( exprStmt->expr, indexer );
472        }
473
474        void Resolver::previsit( AsmExpr *asmExpr ) {
475                visit_children = false;
476                findVoidExpression( asmExpr->operand, indexer );
477                if ( asmExpr->get_inout() ) {
478                        findVoidExpression( asmExpr->inout, indexer );
479                } // if
480        }
481
482        void Resolver::previsit( AsmStmt *asmStmt ) {
483                visit_children = false;
484                acceptAll( asmStmt->get_input(), *visitor );
485                acceptAll( asmStmt->get_output(), *visitor );
486        }
487
488        void Resolver::previsit( IfStmt *ifStmt ) {
489                findIntegralExpression( ifStmt->condition, indexer );
490        }
491
492        void Resolver::previsit( WhileStmt *whileStmt ) {
493                findIntegralExpression( whileStmt->condition, indexer );
494        }
495
496        void Resolver::previsit( ForStmt *forStmt ) {
497                if ( forStmt->condition ) {
498                        findIntegralExpression( forStmt->condition, indexer );
499                } // if
500
501                if ( forStmt->increment ) {
502                        findVoidExpression( forStmt->increment, indexer );
503                } // if
504        }
505
506        void Resolver::previsit( SwitchStmt *switchStmt ) {
507                GuardValue( currentObject );
508                findIntegralExpression( switchStmt->condition, indexer );
509
510                currentObject = CurrentObject( switchStmt->condition->result );
511        }
512
513        void Resolver::previsit( CaseStmt *caseStmt ) {
514                if ( caseStmt->condition ) {
515                        std::list< InitAlternative > initAlts = currentObject.getOptions();
516                        assertf( initAlts.size() == 1, "SwitchStmt did not correctly resolve an integral expression." );
517                        // must remove cast from case statement because RangeExpr cannot be cast.
518                        Expression * newExpr = new CastExpr( caseStmt->condition, initAlts.front().type->clone() );
519                        findSingleExpression( newExpr, indexer );
520                        // case condition cannot have a cast in C, so it must be removed, regardless of whether it performs a conversion.
521                        // Ideally we would perform the conversion internally here.
522                        if ( CastExpr * castExpr = dynamic_cast< CastExpr * >( newExpr ) ) {
523                                newExpr = castExpr->arg;
524                                castExpr->arg = nullptr;
525                                std::swap( newExpr->env, castExpr->env );
526                                delete castExpr;
527                        }
528                        caseStmt->condition = newExpr;
529                }
530        }
531
532        void Resolver::previsit( BranchStmt *branchStmt ) {
533                visit_children = false;
534                // must resolve the argument for a computed goto
535                if ( branchStmt->get_type() == BranchStmt::Goto ) { // check for computed goto statement
536                        if ( branchStmt->computedTarget ) {
537                                // computed goto argument is void *
538                                findSingleExpression( branchStmt->computedTarget, new PointerType( Type::Qualifiers(), new VoidType( Type::Qualifiers() ) ), indexer );
539                        } // if
540                } // if
541        }
542
543        void Resolver::previsit( ReturnStmt *returnStmt ) {
544                visit_children = false;
545                if ( returnStmt->expr ) {
546                        findSingleExpression( returnStmt->expr, functionReturn->clone(), indexer );
547                } // if
548        }
549
550        void Resolver::previsit( ThrowStmt *throwStmt ) {
551                visit_children = false;
552                // TODO: Replace *exception type with &exception type.
553                if ( throwStmt->get_expr() ) {
554                        StructDecl * exception_decl =
555                                indexer.lookupStruct( "__cfaabi_ehm__base_exception_t" );
556                        assert( exception_decl );
557                        Type * exceptType = new PointerType( noQualifiers, new StructInstType( noQualifiers, exception_decl ) );
558                        findSingleExpression( throwStmt->expr, exceptType, indexer );
559                }
560        }
561
562        void Resolver::previsit( CatchStmt *catchStmt ) {
563                if ( catchStmt->cond ) {
564                        findSingleExpression( catchStmt->cond, new BasicType( noQualifiers, BasicType::Bool ), indexer );
565                }
566        }
567
568        template< typename iterator_t >
569        inline bool advance_to_mutex( iterator_t & it, const iterator_t & end ) {
570                while( it != end && !(*it)->get_type()->get_mutex() ) {
571                        it++;
572                }
573
574                return it != end;
575        }
576
577        void Resolver::previsit( WaitForStmt * stmt ) {
578                visit_children = false;
579
580                // Resolve all clauses first
581                for( auto& clause : stmt->clauses ) {
582
583                        TypeEnvironment env;
584                        AlternativeFinder funcFinder( indexer, env );
585
586                        // Find all alternatives for a function in canonical form
587                        funcFinder.findWithAdjustment( clause.target.function );
588
589                        if ( funcFinder.get_alternatives().empty() ) {
590                                stringstream ss;
591                                ss << "Use of undeclared indentifier '";
592                                ss << strict_dynamic_cast<NameExpr*>( clause.target.function )->name;
593                                ss << "' in call to waitfor";
594                                SemanticError( stmt->location, ss.str() );
595                        }
596
597                        if(clause.target.arguments.empty()) {
598                                SemanticError( stmt->location, "Waitfor clause must have at least one mutex parameter");
599                        }
600
601                        // Find all alternatives for all arguments in canonical form
602                        std::vector< AlternativeFinder > argAlternatives;
603                        funcFinder.findSubExprs( clause.target.arguments.begin(), clause.target.arguments.end(), back_inserter( argAlternatives ) );
604
605                        // List all combinations of arguments
606                        std::vector< AltList > possibilities;
607                        combos( argAlternatives.begin(), argAlternatives.end(), back_inserter( possibilities ) );
608
609                        AltList                func_candidates;
610                        std::vector< AltList > args_candidates;
611
612                        // For every possible function :
613                        //      try matching the arguments to the parameters
614                        //      not the other way around because we have more arguments than parameters
615                        SemanticErrorException errors;
616                        for ( Alternative & func : funcFinder.get_alternatives() ) {
617                                try {
618                                        PointerType * pointer = dynamic_cast< PointerType* >( func.expr->get_result()->stripReferences() );
619                                        if( !pointer ) {
620                                                SemanticError( func.expr->get_result(), "candidate not viable: not a pointer type\n" );
621                                        }
622
623                                        FunctionType * function = dynamic_cast< FunctionType* >( pointer->get_base() );
624                                        if( !function ) {
625                                                SemanticError( pointer->get_base(), "candidate not viable: not a function type\n" );
626                                        }
627
628
629                                        {
630                                                auto param     = function->parameters.begin();
631                                                auto param_end = function->parameters.end();
632
633                                                if( !advance_to_mutex( param, param_end ) ) {
634                                                        SemanticError(function, "candidate function not viable: no mutex parameters\n");
635                                                }
636                                        }
637
638                                        Alternative newFunc( func );
639                                        // Strip reference from function
640                                        referenceToRvalueConversion( newFunc.expr, newFunc.cost );
641
642                                        // For all the set of arguments we have try to match it with the parameter of the current function alternative
643                                        for ( auto & argsList : possibilities ) {
644
645                                                try {
646                                                        // Declare data structures need for resolution
647                                                        OpenVarSet openVars;
648                                                        AssertionSet resultNeed, resultHave;
649                                                        TypeEnvironment resultEnv( func.env );
650                                                        makeUnifiableVars( function, openVars, resultNeed );
651                                                        // add all type variables as open variables now so that those not used in the parameter
652                                                        // list are still considered open.
653                                                        resultEnv.add( function->forall );
654
655                                                        // Load type variables from arguemnts into one shared space
656                                                        simpleCombineEnvironments( argsList.begin(), argsList.end(), resultEnv );
657
658                                                        // Make sure we don't widen any existing bindings
659                                                        resultEnv.forbidWidening();
660
661                                                        // Find any unbound type variables
662                                                        resultEnv.extractOpenVars( openVars );
663
664                                                        auto param     = function->parameters.begin();
665                                                        auto param_end = function->parameters.end();
666
667                                                        int n_mutex_param = 0;
668
669                                                        // For every arguments of its set, check if it matches one of the parameter
670                                                        // The order is important
671                                                        for( auto & arg : argsList ) {
672
673                                                                // Ignore non-mutex arguments
674                                                                if( !advance_to_mutex( param, param_end ) ) {
675                                                                        // We ran out of parameters but still have arguments
676                                                                        // this function doesn't match
677                                                                        SemanticError( function, toString("candidate function not viable: too many mutex arguments, expected ", n_mutex_param, "\n" ));
678                                                                }
679
680                                                                n_mutex_param++;
681
682                                                                // Check if the argument matches the parameter type in the current scope
683                                                                if( ! unify( arg.expr->get_result(), (*param)->get_type(), resultEnv, resultNeed, resultHave, openVars, this->indexer ) ) {
684                                                                        // Type doesn't match
685                                                                        stringstream ss;
686                                                                        ss << "candidate function not viable: no known convertion from '";
687                                                                        (*param)->get_type()->print( ss );
688                                                                        ss << "' to '";
689                                                                        arg.expr->get_result()->print( ss );
690                                                                        ss << "' with env '";
691                                                                        resultEnv.print(ss);
692                                                                        ss << "'\n";
693                                                                        SemanticError( function, ss.str() );
694                                                                }
695
696                                                                param++;
697                                                        }
698
699                                                        // All arguments match !
700
701                                                        // Check if parameters are missing
702                                                        if( advance_to_mutex( param, param_end ) ) {
703                                                                do {
704                                                                        n_mutex_param++;
705                                                                        param++;
706                                                                } while( advance_to_mutex( param, param_end ) );
707
708                                                                // We ran out of arguments but still have parameters left
709                                                                // this function doesn't match
710                                                                SemanticError( function, toString("candidate function not viable: too few mutex arguments, expected ", n_mutex_param, "\n" ));
711                                                        }
712
713                                                        // All parameters match !
714
715                                                        // Finish the expressions to tie in the proper environments
716                                                        finishExpr( newFunc.expr, resultEnv );
717                                                        for( Alternative & alt : argsList ) {
718                                                                finishExpr( alt.expr, resultEnv );
719                                                        }
720
721                                                        // This is a match store it and save it for later
722                                                        func_candidates.push_back( newFunc );
723                                                        args_candidates.push_back( argsList );
724
725                                                }
726                                                catch( SemanticErrorException &e ) {
727                                                        errors.append( e );
728                                                }
729                                        }
730                                }
731                                catch( SemanticErrorException &e ) {
732                                        errors.append( e );
733                                }
734                        }
735
736                        // Make sure we got the right number of arguments
737                        if( func_candidates.empty() )    { SemanticErrorException top( stmt->location, "No alternatives for function in call to waitfor"  ); top.append( errors ); throw top; }
738                        if( args_candidates.empty() )    { SemanticErrorException top( stmt->location, "No alternatives for arguments in call to waitfor" ); top.append( errors ); throw top; }
739                        if( func_candidates.size() > 1 ) { SemanticErrorException top( stmt->location, "Ambiguous function in call to waitfor"            ); top.append( errors ); throw top; }
740                        if( args_candidates.size() > 1 ) { SemanticErrorException top( stmt->location, "Ambiguous arguments in call to waitfor"           ); top.append( errors ); throw top; }
741                        // TODO: need to use findDeletedExpr to ensure no deleted identifiers are used.
742
743                        // Swap the results from the alternative with the unresolved values.
744                        // Alternatives will handle deletion on destruction
745                        std::swap( clause.target.function, func_candidates.front().expr );
746                        for( auto arg_pair : group_iterate( clause.target.arguments, args_candidates.front() ) ) {
747                                std::swap ( std::get<0>( arg_pair), std::get<1>( arg_pair).expr );
748                        }
749
750                        // Resolve the conditions as if it were an IfStmt
751                        // Resolve the statments normally
752                        findSingleExpression( clause.condition, this->indexer );
753                        clause.statement->accept( *visitor );
754                }
755
756
757                if( stmt->timeout.statement ) {
758                        // Resolve the timeout as an size_t for now
759                        // Resolve the conditions as if it were an IfStmt
760                        // Resolve the statments normally
761                        findSingleExpression( stmt->timeout.time, new BasicType( noQualifiers, BasicType::LongLongUnsignedInt ), this->indexer );
762                        findSingleExpression( stmt->timeout.condition, this->indexer );
763                        stmt->timeout.statement->accept( *visitor );
764                }
765
766                if( stmt->orelse.statement ) {
767                        // Resolve the conditions as if it were an IfStmt
768                        // Resolve the statments normally
769                        findSingleExpression( stmt->orelse.condition, this->indexer );
770                        stmt->orelse.statement->accept( *visitor );
771                }
772        }
773
774        template< typename T >
775        bool isCharType( T t ) {
776                if ( BasicType * bt = dynamic_cast< BasicType * >( t ) ) {
777                        return bt->get_kind() == BasicType::Char || bt->get_kind() == BasicType::SignedChar ||
778                                bt->get_kind() == BasicType::UnsignedChar;
779                }
780                return false;
781        }
782
783        void Resolver::previsit( SingleInit *singleInit ) {
784                visit_children = false;
785                // resolve initialization using the possibilities as determined by the currentObject cursor
786                Expression * newExpr = new UntypedInitExpr( singleInit->value, currentObject.getOptions() );
787                findSingleExpression( newExpr, indexer );
788                InitExpr * initExpr = strict_dynamic_cast< InitExpr * >( newExpr );
789
790                // move cursor to the object that is actually initialized
791                currentObject.setNext( initExpr->get_designation() );
792
793                // discard InitExpr wrapper and retain relevant pieces
794                newExpr = initExpr->expr;
795                initExpr->expr = nullptr;
796                std::swap( initExpr->env, newExpr->env );
797                // InitExpr may have inferParams in the case where the expression specializes a function
798                // pointer, and newExpr may already have inferParams of its own, so a simple swap is not
799                // sufficient.
800                newExpr->spliceInferParams( initExpr );
801                delete initExpr;
802
803                // get the actual object's type (may not exactly match what comes back from the resolver
804                // due to conversions)
805                Type * initContext = currentObject.getCurrentType();
806
807                removeExtraneousCast( newExpr, indexer );
808
809                // check if actual object's type is char[]
810                if ( ArrayType * at = dynamic_cast< ArrayType * >( initContext ) ) {
811                        if ( isCharType( at->get_base() ) ) {
812                                // check if the resolved type is char *
813                                if ( PointerType * pt = dynamic_cast< PointerType *>( newExpr->get_result() ) ) {
814                                        if ( isCharType( pt->get_base() ) ) {
815                                                if ( CastExpr *ce = dynamic_cast< CastExpr * >( newExpr ) ) {
816                                                        // strip cast if we're initializing a char[] with a char *,
817                                                        // e.g.  char x[] = "hello";
818                                                        newExpr = ce->get_arg();
819                                                        ce->set_arg( nullptr );
820                                                        std::swap( ce->env, newExpr->env );
821                                                        delete ce;
822                                                }
823                                        }
824                                }
825                        }
826                }
827
828                // set initializer expr to resolved express
829                singleInit->value = newExpr;
830
831                // move cursor to next object in preparation for next initializer
832                currentObject.increment();
833        }
834
835        void Resolver::previsit( ListInit * listInit ) {
836                visit_children = false;
837                // move cursor into brace-enclosed initializer-list
838                currentObject.enterListInit();
839                // xxx - fix this so that the list isn't copied, iterator should be used to change current
840                // element
841                std::list<Designation *> newDesignations;
842                for ( auto p : group_iterate(listInit->get_designations(), listInit->get_initializers()) ) {
843                        // iterate designations and initializers in pairs, moving the cursor to the current
844                        // designated object and resolving the initializer against that object.
845                        Designation * des = std::get<0>(p);
846                        Initializer * init = std::get<1>(p);
847                        newDesignations.push_back( currentObject.findNext( des ) );
848                        init->accept( *visitor );
849                }
850                // set the set of 'resolved' designations and leave the brace-enclosed initializer-list
851                listInit->get_designations() = newDesignations; // xxx - memory management
852                currentObject.exitListInit();
853
854                // xxx - this part has not be folded into CurrentObject yet
855                // } else if ( TypeInstType * tt = dynamic_cast< TypeInstType * >( initContext ) ) {
856                //      Type * base = tt->get_baseType()->get_base();
857                //      if ( base ) {
858                //              // know the implementation type, so try using that as the initContext
859                //              ObjectDecl tmpObj( "", Type::StorageClasses(), LinkageSpec::Cforall, nullptr, base->clone(), nullptr );
860                //              currentObject = &tmpObj;
861                //              visit( listInit );
862                //      } else {
863                //              // missing implementation type -- might be an unknown type variable, so try proceeding with the current init context
864                //              Parent::visit( listInit );
865                //      }
866                // } else {
867        }
868
869        // ConstructorInit - fall back on C-style initializer
870        void Resolver::fallbackInit( ConstructorInit * ctorInit ) {
871                // could not find valid constructor, or found an intrinsic constructor
872                // fall back on C-style initializer
873                delete ctorInit->get_ctor();
874                ctorInit->set_ctor( nullptr );
875                delete ctorInit->get_dtor();
876                ctorInit->set_dtor( nullptr );
877                maybeAccept( ctorInit->get_init(), *visitor );
878        }
879
880        // needs to be callable from outside the resolver, so this is a standalone function
881        void resolveCtorInit( ConstructorInit * ctorInit, const SymTab::Indexer & indexer ) {
882                assert( ctorInit );
883                PassVisitor<Resolver> resolver( indexer );
884                ctorInit->accept( resolver );
885        }
886
887        void resolveStmtExpr( StmtExpr * stmtExpr, const SymTab::Indexer & indexer ) {
888                assert( stmtExpr );
889                PassVisitor<Resolver> resolver( indexer );
890                stmtExpr->accept( resolver );
891                stmtExpr->computeResult();
892                // xxx - aggregate the environments from all statements? Possibly in AlternativeFinder instead?
893        }
894
895        void Resolver::previsit( ConstructorInit *ctorInit ) {
896                visit_children = false;
897                // xxx - fallback init has been removed => remove fallbackInit function and remove complexity from FixInit and remove C-init from ConstructorInit
898                maybeAccept( ctorInit->ctor, *visitor );
899                maybeAccept( ctorInit->dtor, *visitor );
900
901                // found a constructor - can get rid of C-style initializer
902                delete ctorInit->init;
903                ctorInit->init = nullptr;
904
905                // intrinsic single parameter constructors and destructors do nothing. Since this was
906                // implicitly generated, there's no way for it to have side effects, so get rid of it
907                // to clean up generated code.
908                if ( InitTweak::isIntrinsicSingleArgCallStmt( ctorInit->ctor ) ) {
909                        delete ctorInit->ctor;
910                        ctorInit->ctor = nullptr;
911                }
912
913                if ( InitTweak::isIntrinsicSingleArgCallStmt( ctorInit->dtor ) ) {
914                        delete ctorInit->dtor;
915                        ctorInit->dtor = nullptr;
916                }
917
918                // xxx - todo -- what about arrays?
919                // if ( dtor == nullptr && InitTweak::isIntrinsicCallStmt( ctorInit->get_ctor() ) ) {
920                //      // can reduce the constructor down to a SingleInit using the
921                //      // second argument from the ctor call, since
922                //      delete ctorInit->get_ctor();
923                //      ctorInit->set_ctor( nullptr );
924
925                //      Expression * arg =
926                //      ctorInit->set_init( new SingleInit( arg ) );
927                // }
928        }
929} // namespace ResolvExpr
930
931// Local Variables: //
932// tab-width: 4 //
933// mode: c++ //
934// compile-command: "make install" //
935// End: //
Note: See TracBrowser for help on using the repository browser.