source: src/ResolvExpr/Resolver.cc@ bc4bea8

ADT arm-eh ast-experimental enum forall-pointer-decay jacob/cs343-translation jenkins-sandbox new-ast new-ast-unique-expr pthread-emulation qualifiedEnum
Last change on this file since bc4bea8 was 8d70648, checked in by Aaron Moss <a3moss@…>, 6 years ago

Merge branch 'master' of plg.uwaterloo.ca:software/cfa/cfa-cc

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