source: src/ResolvExpr/Resolver.cc@ cde3891

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 cde3891 was cde3891, checked in by Thierry Delisle <tdelisle@…>, 7 years ago

Merge branch 'master' into cleanup-dtors

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