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