source: src/ResolvExpr/Resolver.cc@ 2bfc6b2

ADT arm-eh ast-experimental cleanup-dtors enum forall-pointer-decay jacob/cs343-translation jenkins-sandbox new-ast new-ast-unique-expr pthread-emulation qualifiedEnum
Last change on this file since 2bfc6b2 was 2bfc6b2, checked in by Rob Schluntz <rschlunt@…>, 7 years ago

Refactor FindSpecialDeclarations and associated special declarations

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