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