source: src/ResolvExpr/AlternativeFinder.cc@ fed6a0f

ADT ast-experimental
Last change on this file since fed6a0f was fed6a0f, checked in by Andrew Beach <ajbeach@…>, 3 years ago

Header Clean-up: Moving more declarations to the header of the implementation file.

  • Property mode set to 100644
File size: 71.9 KB
RevLine 
[a32b204]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//
[6ed1d4b]7// AlternativeFinder.cc --
[a32b204]8//
9// Author : Richard C. Bilson
10// Created On : Sat May 16 23:52:08 2015
[7d01cf44]11// Last Modified By : Andrew Beach
12// Last Modified On : Thu Aug 8 16:35:00 2019
13// Update Count : 38
[a32b204]14//
15
[fed6a0f]16#include "AlternativeFinder.h"
17
[ea6332d]18#include <algorithm> // for copy
[e3e16bc]19#include <cassert> // for strict_dynamic_cast, assert, assertf
[403b388]20#include <cstddef> // for size_t
[ea6332d]21#include <iostream> // for operator<<, cerr, ostream, endl
22#include <iterator> // for back_insert_iterator, back_inserter
23#include <list> // for _List_iterator, list, _List_const_...
24#include <map> // for _Rb_tree_iterator, map, _Rb_tree_c...
[403b388]25#include <memory> // for allocator_traits<>::value_type, unique_ptr
[ea6332d]26#include <utility> // for pair
[aeb75b1]27#include <vector> // for vector
[51b73452]28
[3bbd012]29#include "CompilationState.h" // for resolvep
[ea6332d]30#include "Alternative.h" // for AltList, Alternative
[d76c588]31#include "AST/Expr.hpp"
[4b7cce6]32#include "AST/SymbolTable.hpp"
[d76c588]33#include "AST/Type.hpp"
[ea6332d]34#include "Common/SemanticError.h" // for SemanticError
35#include "Common/utility.h" // for deleteAll, printAll, CodeLocation
[fed6a0f]36#include "ConversionCost.h" // for conversionCost
[ea6332d]37#include "Cost.h" // for Cost, Cost::zero, operator<<, Cost...
[a8b27c6]38#include "ExplodedActual.h" // for ExplodedActual
[ea6332d]39#include "InitTweak/InitTweak.h" // for getFunctionName
40#include "RenameVars.h" // for RenameVars, global_renamer
[6d6e829]41#include "ResolveAssertions.h" // for resolveAssertions
[ea6332d]42#include "ResolveTypeof.h" // for resolveTypeof
43#include "Resolver.h" // for resolveStmtExpr
44#include "SymTab/Indexer.h" // for Indexer
45#include "SymTab/Mangler.h" // for Mangler
[9939dc3]46#include "SymTab/ValidateType.h" // for validateType
[ea6332d]47#include "SynTree/Constant.h" // for Constant
48#include "SynTree/Declaration.h" // for DeclarationWithType, TypeDecl, Dec...
49#include "SynTree/Expression.h" // for Expression, CastExpr, NameExpr
50#include "SynTree/Initializer.h" // for SingleInit, operator<<, Designation
51#include "SynTree/SynTree.h" // for UniqueId
52#include "SynTree/Type.h" // for Type, FunctionType, PointerType
53#include "Tuples/Explode.h" // for explode
54#include "Tuples/Tuples.h" // for isTtype, handleTupleAssignment
55#include "Unify.h" // for unify
56#include "typeops.h" // for adjustExprType, polyCost, castCost
[51b73452]57
[6ed1d4b]58#define PRINT( text ) if ( resolvep ) { text }
[51b73452]59//#define DEBUG_COST
60
61namespace ResolvExpr {
[13deae88]62 struct AlternativeFinder::Finder : public WithShortCircuiting {
63 Finder( AlternativeFinder & altFinder ) : altFinder( altFinder ), indexer( altFinder.indexer ), alternatives( altFinder.alternatives ), env( altFinder.env ), targetType( altFinder.targetType ) {}
64
65 void previsit( BaseSyntaxNode * ) { visit_children = false; }
66
67 void postvisit( ApplicationExpr * applicationExpr );
68 void postvisit( UntypedExpr * untypedExpr );
69 void postvisit( AddressExpr * addressExpr );
70 void postvisit( LabelAddressExpr * labelExpr );
71 void postvisit( CastExpr * castExpr );
72 void postvisit( VirtualCastExpr * castExpr );
[3b0c8cb]73 void postvisit( KeywordCastExpr * castExpr );
[13deae88]74 void postvisit( UntypedMemberExpr * memberExpr );
75 void postvisit( MemberExpr * memberExpr );
76 void postvisit( NameExpr * variableExpr );
77 void postvisit( VariableExpr * variableExpr );
78 void postvisit( ConstantExpr * constantExpr );
79 void postvisit( SizeofExpr * sizeofExpr );
80 void postvisit( AlignofExpr * alignofExpr );
81 void postvisit( UntypedOffsetofExpr * offsetofExpr );
82 void postvisit( OffsetofExpr * offsetofExpr );
83 void postvisit( OffsetPackExpr * offsetPackExpr );
84 void postvisit( LogicalExpr * logicalExpr );
85 void postvisit( ConditionalExpr * conditionalExpr );
86 void postvisit( CommaExpr * commaExpr );
87 void postvisit( ImplicitCopyCtorExpr * impCpCtorExpr );
88 void postvisit( ConstructorExpr * ctorExpr );
89 void postvisit( RangeExpr * rangeExpr );
90 void postvisit( UntypedTupleExpr * tupleExpr );
91 void postvisit( TupleExpr * tupleExpr );
92 void postvisit( TupleIndexExpr * tupleExpr );
93 void postvisit( TupleAssignExpr * tupleExpr );
94 void postvisit( UniqueExpr * unqExpr );
95 void postvisit( StmtExpr * stmtExpr );
96 void postvisit( UntypedInitExpr * initExpr );
[c71b256]97 void postvisit( InitExpr * initExpr );
98 void postvisit( DeletedExpr * delExpr );
[d807ca28]99 void postvisit( GenericExpr * genExpr );
[13deae88]100
101 /// Adds alternatives for anonymous members
102 void addAnonConversions( const Alternative & alt );
103 /// Adds alternatives for member expressions, given the aggregate, conversion cost for that aggregate, and name of the member
[6d6e829]104 template< typename StructOrUnionType > void addAggMembers( StructOrUnionType *aggInst, Expression *expr, const Alternative &alt, const Cost &newCost, const std::string & name );
[13deae88]105 /// Adds alternatives for member expressions where the left side has tuple type
[6d6e829]106 void addTupleMembers( TupleType *tupleType, Expression *expr, const Alternative &alt, const Cost &newCost, Expression *member );
[13deae88]107 /// Adds alternatives for offsetof expressions, given the base type and name of the member
108 template< typename StructOrUnionType > void addOffsetof( StructOrUnionType *aggInst, const std::string &name );
109 /// Takes a final result and checks if its assertions can be satisfied
110 template<typename OutputIterator>
111 void validateFunctionAlternative( const Alternative &func, ArgPack& result, const std::vector<ArgPack>& results, OutputIterator out );
112 /// Finds matching alternatives for a function, given a set of arguments
113 template<typename OutputIterator>
[432ce7a]114 void makeFunctionAlternatives( const Alternative &func, FunctionType *funcType, const ExplodedArgs_old& args, OutputIterator out );
[0b00df0]115 /// Sets up parameter inference for an output alternative
[13deae88]116 template< typename OutputIterator >
[0b00df0]117 void inferParameters( Alternative &newAlt, OutputIterator out );
[13deae88]118 private:
119 AlternativeFinder & altFinder;
120 const SymTab::Indexer &indexer;
121 AltList & alternatives;
122 const TypeEnvironment &env;
123 Type *& targetType;
124 };
125
[908cc83]126 Cost sumCost( const AltList &in ) {
[89be1c68]127 Cost total = Cost::zero;
[908cc83]128 for ( AltList::const_iterator i = in.begin(); i != in.end(); ++i ) {
129 total += i->cost;
130 }
131 return total;
132 }
133
[1e8bbac9]134 void printAlts( const AltList &list, std::ostream &os, unsigned int indentAmt ) {
[2595df1]135 std::vector<std::string> sorted;
136 sorted.reserve(list.size());
137 for(const auto & c : list) {
138 std::stringstream ss;
[3233b91]139 c.print( ss, indentAmt );
[2595df1]140 sorted.push_back(ss.str());
141 }
[1db306a]142
[2595df1]143 std::sort(sorted.begin(), sorted.end());
[1db306a]144
[2595df1]145 for ( const auto & s : sorted ) {
146 os << s << std::endl;
[a32b204]147 }
[1e8bbac9]148 }
[d9a0e76]149
[1e8bbac9]150 namespace {
[a32b204]151 void makeExprList( const AltList &in, std::list< Expression* > &out ) {
152 for ( AltList::const_iterator i = in.begin(); i != in.end(); ++i ) {
153 out.push_back( i->expr->clone() );
154 }
155 }
[d9a0e76]156
[a32b204]157 struct PruneStruct {
158 bool isAmbiguous;
159 AltList::iterator candidate;
160 PruneStruct() {}
161 PruneStruct( AltList::iterator candidate ): isAmbiguous( false ), candidate( candidate ) {}
162 };
163
[0f19d763]164 /// Prunes a list of alternatives down to those that have the minimum conversion cost for a given return type; skips ambiguous interpretations
[a32b204]165 template< typename InputIterator, typename OutputIterator >
[d7dc824]166 void pruneAlternatives( InputIterator begin, InputIterator end, OutputIterator out ) {
[a32b204]167 // select the alternatives that have the minimum conversion cost for a particular set of result types
168 std::map< std::string, PruneStruct > selected;
169 for ( AltList::iterator candidate = begin; candidate != end; ++candidate ) {
170 PruneStruct current( candidate );
171 std::string mangleName;
[906e24d]172 {
173 Type * newType = candidate->expr->get_result()->clone();
[a32b204]174 candidate->env.apply( newType );
[906e24d]175 mangleName = SymTab::Mangler::mangle( newType );
[a32b204]176 delete newType;
177 }
178 std::map< std::string, PruneStruct >::iterator mapPlace = selected.find( mangleName );
179 if ( mapPlace != selected.end() ) {
180 if ( candidate->cost < mapPlace->second.candidate->cost ) {
181 PRINT(
[6ed1d4b]182 std::cerr << "cost " << candidate->cost << " beats " << mapPlace->second.candidate->cost << std::endl;
[7c64920]183 )
[0f19d763]184 selected[ mangleName ] = current;
[a32b204]185 } else if ( candidate->cost == mapPlace->second.candidate->cost ) {
[630bcb5]186 // if one of the candidates contains a deleted identifier, can pick the other, since
187 // deleted expressions should not be ambiguous if there is another option that is at least as good
188 if ( findDeletedExpr( candidate->expr ) ) {
189 // do nothing
190 PRINT( std::cerr << "candidate is deleted" << std::endl; )
191 } else if ( findDeletedExpr( mapPlace->second.candidate->expr ) ) {
192 PRINT( std::cerr << "current is deleted" << std::endl; )
193 selected[ mangleName ] = current;
194 } else {
195 PRINT(
196 std::cerr << "marking ambiguous" << std::endl;
197 )
198 mapPlace->second.isAmbiguous = true;
199 }
[b0837e4]200 } else {
201 PRINT(
202 std::cerr << "cost " << candidate->cost << " loses to " << mapPlace->second.candidate->cost << std::endl;
203 )
[a32b204]204 }
205 } else {
206 selected[ mangleName ] = current;
207 }
208 }
[d9a0e76]209
[0f19d763]210 // accept the alternatives that were unambiguous
211 for ( std::map< std::string, PruneStruct >::iterator target = selected.begin(); target != selected.end(); ++target ) {
212 if ( ! target->second.isAmbiguous ) {
213 Alternative &alt = *target->second.candidate;
[906e24d]214 alt.env.applyFree( alt.expr->get_result() );
[0f19d763]215 *out++ = alt;
[a32b204]216 }
[0f19d763]217 }
[d9a0e76]218 }
[a32b204]219
220 void renameTypes( Expression *expr ) {
[ad51cc2]221 renameTyVars( expr->result );
[e76acbe]222 }
[1dcd9554]223 } // namespace
[b1bead1]224
[a181494]225 void referenceToRvalueConversion( Expression *& expr, Cost & cost ) {
[1dcd9554]226 if ( dynamic_cast< ReferenceType * >( expr->get_result() ) ) {
227 // cast away reference from expr
228 expr = new CastExpr( expr, expr->get_result()->stripReferences()->clone() );
[a181494]229 cost.incReference();
[b1bead1]230 }
[1dcd9554]231 }
[d9a0e76]232
[a32b204]233 template< typename InputIterator, typename OutputIterator >
234 void AlternativeFinder::findSubExprs( InputIterator begin, InputIterator end, OutputIterator out ) {
235 while ( begin != end ) {
236 AlternativeFinder finder( indexer, env );
237 finder.findWithAdjustment( *begin );
238 // XXX either this
239 //Designators::fixDesignations( finder, (*begin++)->get_argName() );
240 // or XXX this
241 begin++;
242 PRINT(
[6ed1d4b]243 std::cerr << "findSubExprs" << std::endl;
244 printAlts( finder.alternatives, std::cerr );
[7c64920]245 )
[0f19d763]246 *out++ = finder;
[a32b204]247 }
[d9a0e76]248 }
249
[a32b204]250 AlternativeFinder::AlternativeFinder( const SymTab::Indexer &indexer, const TypeEnvironment &env )
251 : indexer( indexer ), env( env ) {
[d9a0e76]252 }
[51b73452]253
[59cf83b]254 void AlternativeFinder::find( Expression *expr, ResolvMode mode ) {
[13deae88]255 PassVisitor<Finder> finder( *this );
256 expr->accept( finder );
[59cf83b]257 if ( mode.failFast && alternatives.empty() ) {
[83882e9]258 PRINT(
259 std::cerr << "No reasonable alternatives for expression " << expr << std::endl;
260 )
[a16764a6]261 SemanticError( expr, "No reasonable alternatives for expression " );
[a32b204]262 }
[1389810]263 if ( mode.prune ) {
[6d6e829]264 // trim candidates just to those where the assertions resolve
[fbecee5]265 // - necessary pre-requisite to pruning
[6d6e829]266 AltList candidates;
[4d2d45f9]267 std::list<std::string> errors;
[6d6e829]268 for ( unsigned i = 0; i < alternatives.size(); ++i ) {
[4d2d45f9]269 resolveAssertions( alternatives[i], indexer, candidates, errors );
[6d6e829]270 }
271 // fail early if none such
272 if ( mode.failFast && candidates.empty() ) {
273 std::ostringstream stream;
[4d2d45f9]274 stream << "No alternatives with satisfiable assertions for " << expr << "\n";
275 // << "Alternatives with failing assertions are:\n";
276 // printAlts( alternatives, stream, 1 );
277 for ( const auto& err : errors ) {
278 stream << err;
279 }
[6d6e829]280 SemanticError( expr->location, stream.str() );
281 }
282 // reset alternatives
283 alternatives = std::move( candidates );
284 }
[59cf83b]285 if ( mode.prune ) {
[b0837e4]286 auto oldsize = alternatives.size();
[b6fe7e6]287 PRINT(
288 std::cerr << "alternatives before prune:" << std::endl;
289 printAlts( alternatives, std::cerr );
290 )
[bd4f2e9]291 AltList pruned;
292 pruneAlternatives( alternatives.begin(), alternatives.end(), back_inserter( pruned ) );
[59cf83b]293 if ( mode.failFast && pruned.empty() ) {
[b6fe7e6]294 std::ostringstream stream;
295 AltList winners;
296 findMinCost( alternatives.begin(), alternatives.end(), back_inserter( winners ) );
[50377a4]297 stream << "Cannot choose between " << winners.size() << " alternatives for expression\n";
[5a824c2]298 expr->print( stream );
[93401f8]299 stream << " Alternatives are:\n";
[50377a4]300 printAlts( winners, stream, 1 );
[a16764a6]301 SemanticError( expr->location, stream.str() );
[b6fe7e6]302 }
[0bd46fd]303 alternatives = std::move(pruned);
[b0837e4]304 PRINT(
305 std::cerr << "there are " << oldsize << " alternatives before elimination" << std::endl;
306 )
[b6fe7e6]307 PRINT(
308 std::cerr << "there are " << alternatives.size() << " alternatives after elimination" << std::endl;
309 )
[a32b204]310 }
[954ef5b]311 // adjust types after pruning so that types substituted by pruneAlternatives are correctly adjusted
[59cf83b]312 if ( mode.adjust ) {
313 for ( Alternative& i : alternatives ) {
314 adjustExprType( i.expr->get_result(), i.env, indexer );
[954ef5b]315 }
316 }
[8e9cbb2]317
[64ac636]318 // Central location to handle gcc extension keyword, etc. for all expression types.
[8e9cbb2]319 for ( Alternative &iter: alternatives ) {
320 iter.expr->set_extension( expr->get_extension() );
[64ac636]321 iter.expr->location = expr->location;
[8e9cbb2]322 } // for
[0f19d763]323 }
[d9a0e76]324
[4e66a18]325 void AlternativeFinder::findWithAdjustment( Expression *expr ) {
[59cf83b]326 find( expr, ResolvMode::withAdjustment() );
[4e66a18]327 }
328
329 void AlternativeFinder::findWithoutPrune( Expression * expr ) {
[59cf83b]330 find( expr, ResolvMode::withoutPrune() );
[4e66a18]331 }
332
333 void AlternativeFinder::maybeFind( Expression * expr ) {
[59cf83b]334 find( expr, ResolvMode::withoutFailFast() );
[d9a0e76]335 }
[a32b204]336
[13deae88]337 void AlternativeFinder::Finder::addAnonConversions( const Alternative & alt ) {
[4b0f997]338 // adds anonymous member interpretations whenever an aggregate value type is seen.
[d1685588]339 // it's okay for the aggregate expression to have reference type -- cast it to the base type to treat the aggregate as the referenced value
340 std::unique_ptr<Expression> aggrExpr( alt.expr->clone() );
[25fcb84]341 alt.env.apply( aggrExpr->result );
342 Type * aggrType = aggrExpr->result;
[d1685588]343 if ( dynamic_cast< ReferenceType * >( aggrType ) ) {
344 aggrType = aggrType->stripReferences();
345 aggrExpr.reset( new CastExpr( aggrExpr.release(), aggrType->clone() ) );
346 }
347
[6f096d2]348 if ( StructInstType * structInst = dynamic_cast< StructInstType* >( aggrExpr->result ) ) {
[6d6e829]349 addAggMembers( structInst, aggrExpr.get(), alt, alt.cost+Cost::safe, "" );
[6f096d2]350 } else if ( UnionInstType * unionInst = dynamic_cast< UnionInstType* >( aggrExpr->result ) ) {
[6d6e829]351 addAggMembers( unionInst, aggrExpr.get(), alt, alt.cost+Cost::safe, "" );
[4b0f997]352 } // if
353 }
[77971f6]354
[a32b204]355 template< typename StructOrUnionType >
[6f096d2]356 void AlternativeFinder::Finder::addAggMembers( StructOrUnionType * aggInst, Expression * expr, const Alternative& alt, const Cost &newCost, const std::string & name ) {
[bf32bb8]357 std::list< Declaration* > members;
358 aggInst->lookup( name, members );
[4b0f997]359
[5de1e2c]360 for ( Declaration * decl : members ) {
[6f096d2]361 if ( DeclarationWithType * dwt = dynamic_cast< DeclarationWithType* >( decl ) ) {
[5de1e2c]362 // addAnonAlternatives uses vector::push_back, which invalidates references to existing elements, so
363 // can't construct in place and use vector::back
[6d6e829]364 Alternative newAlt{ alt, new MemberExpr{ dwt, expr->clone() }, newCost };
[5de1e2c]365 renameTypes( newAlt.expr );
366 addAnonConversions( newAlt ); // add anonymous member interpretations whenever an aggregate value type is seen as a member expression.
367 alternatives.push_back( std::move(newAlt) );
[bf32bb8]368 } else {
369 assert( false );
[a32b204]370 }
371 }
[d9a0e76]372 }
[a32b204]373
[6f096d2]374 void AlternativeFinder::Finder::addTupleMembers( TupleType * tupleType, Expression * expr, const Alternative &alt, const Cost &newCost, Expression * member ) {
[848ce71]375 if ( ConstantExpr * constantExpr = dynamic_cast< ConstantExpr * >( member ) ) {
376 // get the value of the constant expression as an int, must be between 0 and the length of the tuple type to have meaning
[2a6c115]377 auto val = constantExpr->intValue();
[848ce71]378 std::string tmp;
[2a6c115]379 if ( val >= 0 && (unsigned long long)val < tupleType->size() ) {
[6f096d2]380 alternatives.push_back( Alternative{
[6d6e829]381 alt, new TupleIndexExpr( expr->clone(), val ), newCost } );
[2a6c115]382 } // if
[848ce71]383 } // if
384 }
385
[6f096d2]386 void AlternativeFinder::Finder::postvisit( ApplicationExpr * applicationExpr ) {
[6d6e829]387 alternatives.push_back( Alternative{ applicationExpr->clone(), env } );
[d9a0e76]388 }
389
[7d01cf44]390 Cost computeConversionCost( Type * actualType, Type * formalType, bool actualIsLvalue,
391 const SymTab::Indexer &indexer, const TypeEnvironment & env ) {
[ddf8a29]392 PRINT(
393 std::cerr << std::endl << "converting ";
394 actualType->print( std::cerr, 8 );
395 std::cerr << std::endl << " to ";
396 formalType->print( std::cerr, 8 );
397 std::cerr << std::endl << "environment is: ";
398 env.print( std::cerr, 8 );
399 std::cerr << std::endl;
400 )
[7d01cf44]401 Cost convCost = conversionCost( actualType, formalType, actualIsLvalue, indexer, env );
[ddf8a29]402 PRINT(
[d06c808]403 std::cerr << std::endl << "cost is " << convCost << std::endl;
[ddf8a29]404 )
405 if ( convCost == Cost::infinity ) {
406 return convCost;
407 }
408 convCost.incPoly( polyCost( formalType, env, indexer ) + polyCost( actualType, env, indexer ) );
[d06c808]409 PRINT(
410 std::cerr << "cost with polycost is " << convCost << std::endl;
411 )
[ddf8a29]412 return convCost;
413 }
414
415 Cost computeExpressionConversionCost( Expression *& actualExpr, Type * formalType, const SymTab::Indexer &indexer, const TypeEnvironment & env ) {
[7d01cf44]416 Cost convCost = computeConversionCost(
417 actualExpr->result, formalType, actualExpr->get_lvalue(), indexer, env );
[ddf8a29]418
[bb666f64]419 // if there is a non-zero conversion cost, ignoring poly cost, then the expression requires conversion.
420 // ignore poly cost for now, since this requires resolution of the cast to infer parameters and this
421 // does not currently work for the reason stated below.
[ddf8a29]422 Cost tmpCost = convCost;
423 tmpCost.incPoly( -tmpCost.get_polyCost() );
424 if ( tmpCost != Cost::zero ) {
425 Type *newType = formalType->clone();
426 env.apply( newType );
427 actualExpr = new CastExpr( actualExpr, newType );
428 // xxx - SHOULD be able to resolve this cast, but at the moment pointers are not castable to zero_t, but are implicitly convertible. This is clearly
429 // inconsistent, once this is fixed it should be possible to resolve the cast.
430 // xxx - this isn't working, it appears because type1 (the formal type) is seen as widenable, but it shouldn't be, because this makes the conversion from DT* to DT* since commontype(zero_t, DT*) is DT*, rather than just nothing.
431
432 // AlternativeFinder finder( indexer, env );
433 // finder.findWithAdjustment( actualExpr );
434 // assertf( finder.get_alternatives().size() > 0, "Somehow castable expression failed to find alternatives." );
435 // assertf( finder.get_alternatives().size() == 1, "Somehow got multiple alternatives for known cast expression." );
436 // Alternative & alt = finder.get_alternatives().front();
437 // delete actualExpr;
438 // actualExpr = alt.expr->clone();
439 }
440 return convCost;
441 }
442
443 Cost computeApplicationConversionCost( Alternative &alt, const SymTab::Indexer &indexer ) {
[e3e16bc]444 ApplicationExpr *appExpr = strict_dynamic_cast< ApplicationExpr* >( alt.expr );
[1dd1bd2]445 PointerType *pointer = strict_dynamic_cast< PointerType* >( appExpr->function->result );
446 FunctionType *function = strict_dynamic_cast< FunctionType* >( pointer->base );
[a32b204]447
[89be1c68]448 Cost convCost = Cost::zero;
[1dd1bd2]449 std::list< DeclarationWithType* >& formals = function->parameters;
[a32b204]450 std::list< DeclarationWithType* >::iterator formal = formals.begin();
[1dd1bd2]451 std::list< Expression* >& actuals = appExpr->args;
[0362d42]452
[1dd1bd2]453 for ( Expression*& actualExpr : actuals ) {
454 Type * actualType = actualExpr->result;
[a32b204]455 PRINT(
[6ed1d4b]456 std::cerr << "actual expression:" << std::endl;
[1dd1bd2]457 actualExpr->print( std::cerr, 8 );
[6ed1d4b]458 std::cerr << "--- results are" << std::endl;
[53e3b4a]459 actualType->print( std::cerr, 8 );
[7c64920]460 )
[53e3b4a]461 if ( formal == formals.end() ) {
[1dd1bd2]462 if ( function->isVarArgs ) {
[89be1c68]463 convCost.incUnsafe();
[d06c808]464 PRINT( std::cerr << "end of formals with varargs function: inc unsafe: " << convCost << std::endl; ; )
[b1bead1]465 // convert reference-typed expressions to value-typed expressions
[1dd1bd2]466 referenceToRvalueConversion( actualExpr, convCost );
[53e3b4a]467 continue;
468 } else {
469 return Cost::infinity;
[7c64920]470 }
[53e3b4a]471 }
[1dd1bd2]472 if ( DefaultArgExpr * def = dynamic_cast< DefaultArgExpr * >( actualExpr ) ) {
[0f79853]473 // default arguments should be free - don't include conversion cost.
474 // Unwrap them here because they are not relevant to the rest of the system.
[1dd1bd2]475 actualExpr = def->expr;
[0f79853]476 ++formal;
477 continue;
478 }
[1dd1bd2]479 // mark conversion cost to formal and also specialization cost of formal type
[53e3b4a]480 Type * formalType = (*formal)->get_type();
[1dd1bd2]481 convCost += computeExpressionConversionCost( actualExpr, formalType, indexer, alt.env );
482 convCost.decSpec( specCost( formalType ) );
[53e3b4a]483 ++formal; // can't be in for-loop update because of the continue
[d9a0e76]484 }
[a32b204]485 if ( formal != formals.end() ) {
486 return Cost::infinity;
[d9a0e76]487 }
488
[6f096d2]489 // specialization cost of return types can't be accounted for directly, it disables
[bd78797]490 // otherwise-identical calls, like this example based on auto-newline in the I/O lib:
491 //
492 // forall(otype OS) {
493 // void ?|?(OS&, int); // with newline
494 // OS& ?|?(OS&, int); // no newline, always chosen due to more specialization
495 // }
[1dd1bd2]496
497 // mark type variable and specialization cost of forall clause
498 convCost.incVar( function->forall.size() );
499 for ( TypeDecl* td : function->forall ) {
500 convCost.decSpec( td->assertions.size() );
501 }
502
[a32b204]503 return convCost;
504 }
[d9a0e76]505
[8c84ebd]506 /// Adds type variables to the open variable set and marks their assertions
[a32b204]507 void makeUnifiableVars( Type *type, OpenVarSet &unifiableVars, AssertionSet &needAssertions ) {
[43bd69d]508 for ( Type::ForallList::const_iterator tyvar = type->forall.begin(); tyvar != type->forall.end(); ++tyvar ) {
[2c57025]509 unifiableVars[ (*tyvar)->get_name() ] = TypeDecl::Data{ *tyvar };
[43bd69d]510 for ( std::list< DeclarationWithType* >::iterator assert = (*tyvar)->assertions.begin(); assert != (*tyvar)->assertions.end(); ++assert ) {
[6c3a988f]511 needAssertions[ *assert ].isUsed = true;
[a32b204]512 }
[d9a0e76]513 }
514 }
[a32b204]515
[9d5089e]516 /// Unique identifier for matching expression resolutions to their requesting expression (located in CandidateFinder.cpp)
517 extern UniqueId globalResnSlot;
[0b00df0]518
[a32b204]519 template< typename OutputIterator >
[0b00df0]520 void AlternativeFinder::Finder::inferParameters( Alternative &newAlt, OutputIterator out ) {
521 // Set need bindings for any unbound assertions
522 UniqueId crntResnSlot = 0; // matching ID for this expression's assertions
523 for ( auto& assn : newAlt.need ) {
524 // skip already-matched assertions
525 if ( assn.info.resnSlot != 0 ) continue;
526 // assign slot for expression if needed
527 if ( crntResnSlot == 0 ) { crntResnSlot = ++globalResnSlot; }
528 // fix slot to assertion
529 assn.info.resnSlot = crntResnSlot;
530 }
531 // pair slot to expression
532 if ( crntResnSlot != 0 ) { newAlt.expr->resnSlots.push_back( crntResnSlot ); }
533
534 // add to output list, assertion resolution is deferred
[6d6e829]535 *out++ = newAlt;
[d9a0e76]536 }
537
[aeb75b1]538 /// Gets a default value from an initializer, nullptr if not present
539 ConstantExpr* getDefaultValue( Initializer* init ) {
540 if ( SingleInit* si = dynamic_cast<SingleInit*>( init ) ) {
[630bcb5]541 if ( CastExpr* ce = dynamic_cast<CastExpr*>( si->value ) ) {
542 return dynamic_cast<ConstantExpr*>( ce->arg );
543 } else {
544 return dynamic_cast<ConstantExpr*>( si->value );
[aeb75b1]545 }
546 }
547 return nullptr;
548 }
549
550 /// State to iteratively build a match of parameter expressions to arguments
551 struct ArgPack {
[452747a]552 std::size_t parent; ///< Index of parent pack
[403b388]553 std::unique_ptr<Expression> expr; ///< The argument stored here
554 Cost cost; ///< The cost of this argument
555 TypeEnvironment env; ///< Environment for this pack
556 AssertionSet need; ///< Assertions outstanding for this pack
557 AssertionSet have; ///< Assertions found for this pack
558 OpenVarSet openVars; ///< Open variables for this pack
559 unsigned nextArg; ///< Index of next argument in arguments list
560 unsigned tupleStart; ///< Number of tuples that start at this index
[a8b27c6]561 unsigned nextExpl; ///< Index of next exploded element
562 unsigned explAlt; ///< Index of alternative for nextExpl > 0
[403b388]563
564 ArgPack()
[ad51cc2]565 : parent(0), expr(), cost(Cost::zero), env(), need(), have(), openVars(), nextArg(0),
[a8b27c6]566 tupleStart(0), nextExpl(0), explAlt(0) {}
[aeb75b1]567
[11094d9]568 ArgPack(const TypeEnvironment& env, const AssertionSet& need, const AssertionSet& have,
[aeb75b1]569 const OpenVarSet& openVars)
[452747a]570 : parent(0), expr(), cost(Cost::zero), env(env), need(need), have(have),
[a8b27c6]571 openVars(openVars), nextArg(0), tupleStart(0), nextExpl(0), explAlt(0) {}
[11094d9]572
[452747a]573 ArgPack(std::size_t parent, Expression* expr, TypeEnvironment&& env, AssertionSet&& need,
574 AssertionSet&& have, OpenVarSet&& openVars, unsigned nextArg,
[178e4ec]575 unsigned tupleStart = 0, Cost cost = Cost::zero, unsigned nextExpl = 0,
[a8b27c6]576 unsigned explAlt = 0 )
[0bd46fd]577 : parent(parent), expr(expr->clone()), cost(cost), env(std::move(env)), need(std::move(need)),
578 have(std::move(have)), openVars(std::move(openVars)), nextArg(nextArg), tupleStart(tupleStart),
[a8b27c6]579 nextExpl(nextExpl), explAlt(explAlt) {}
[452747a]580
581 ArgPack(const ArgPack& o, TypeEnvironment&& env, AssertionSet&& need, AssertionSet&& have,
[73a5cadb]582 OpenVarSet&& openVars, unsigned nextArg, Cost added )
[452747a]583 : parent(o.parent), expr(o.expr ? o.expr->clone() : nullptr), cost(o.cost + added),
[0bd46fd]584 env(std::move(env)), need(std::move(need)), have(std::move(have)), openVars(std::move(openVars)),
[a8b27c6]585 nextArg(nextArg), tupleStart(o.tupleStart), nextExpl(0), explAlt(0) {}
[73a5cadb]586
[a8b27c6]587 /// true iff this pack is in the middle of an exploded argument
588 bool hasExpl() const { return nextExpl > 0; }
[aeb75b1]589
[a8b27c6]590 /// Gets the list of exploded alternatives for this pack
[432ce7a]591 const ExplodedActual& getExpl( const ExplodedArgs_old& args ) const {
[a8b27c6]592 return args[nextArg-1][explAlt];
593 }
[aeb75b1]594
595 /// Ends a tuple expression, consolidating the appropriate actuals
[403b388]596 void endTuple( const std::vector<ArgPack>& packs ) {
597 // add all expressions in tuple to list, summing cost
[aeb75b1]598 std::list<Expression*> exprs;
[403b388]599 const ArgPack* pack = this;
600 if ( expr ) { exprs.push_front( expr.release() ); }
601 while ( pack->tupleStart == 0 ) {
602 pack = &packs[pack->parent];
603 exprs.push_front( pack->expr->clone() );
604 cost += pack->cost;
[aeb75b1]605 }
[403b388]606 // reset pack to appropriate tuple
607 expr.reset( new TupleExpr( exprs ) );
608 tupleStart = pack->tupleStart - 1;
609 parent = pack->parent;
[aeb75b1]610 }
[4b6ef70]611 };
[aeb75b1]612
613 /// Instantiates an argument to match a formal, returns false if no results left
[11094d9]614 bool instantiateArgument( Type* formalType, Initializer* initializer,
[432ce7a]615 const ExplodedArgs_old& args, std::vector<ArgPack>& results, std::size_t& genStart,
[a8b27c6]616 const SymTab::Indexer& indexer, unsigned nTuples = 0 ) {
[3d2ae8d]617 if ( TupleType * tupleType = dynamic_cast<TupleType*>( formalType ) ) {
[aeb75b1]618 // formalType is a TupleType - group actuals into a TupleExpr
[403b388]619 ++nTuples;
[aeb75b1]620 for ( Type* type : *tupleType ) {
621 // xxx - dropping initializer changes behaviour from previous, but seems correct
[3d2ae8d]622 // ^^^ need to handle the case where a tuple has a default argument
[452747a]623 if ( ! instantiateArgument(
624 type, nullptr, args, results, genStart, indexer, nTuples ) )
[aeb75b1]625 return false;
[403b388]626 nTuples = 0;
627 }
628 // re-consititute tuples for final generation
629 for ( auto i = genStart; i < results.size(); ++i ) {
630 results[i].endTuple( results );
[aeb75b1]631 }
632 return true;
[3d2ae8d]633 } else if ( TypeInstType * ttype = Tuples::isTtype( formalType ) ) {
[aeb75b1]634 // formalType is a ttype, consumes all remaining arguments
635 // xxx - mixing default arguments with variadic??
[403b388]636
637 // completed tuples; will be spliced to end of results to finish
638 std::vector<ArgPack> finalResults{};
639
[aeb75b1]640 // iterate until all results completed
[403b388]641 std::size_t genEnd;
642 ++nTuples;
643 do {
644 genEnd = results.size();
645
[aeb75b1]646 // add another argument to results
[403b388]647 for ( std::size_t i = genStart; i < genEnd; ++i ) {
[a8b27c6]648 auto nextArg = results[i].nextArg;
[452747a]649
[62194cb]650 // use next element of exploded tuple if present
[a8b27c6]651 if ( results[i].hasExpl() ) {
652 const ExplodedActual& expl = results[i].getExpl( args );
[403b388]653
[a8b27c6]654 unsigned nextExpl = results[i].nextExpl + 1;
[62194cb]655 if ( nextExpl == expl.exprs.size() ) {
[a8b27c6]656 nextExpl = 0;
657 }
[403b388]658
659 results.emplace_back(
[178e4ec]660 i, expl.exprs[results[i].nextExpl].get(), copy(results[i].env),
661 copy(results[i].need), copy(results[i].have),
662 copy(results[i].openVars), nextArg, nTuples, Cost::zero, nextExpl,
[62194cb]663 results[i].explAlt );
[452747a]664
[403b388]665 continue;
666 }
[452747a]667
[aeb75b1]668 // finish result when out of arguments
[a8b27c6]669 if ( nextArg >= args.size() ) {
[452747a]670 ArgPack newResult{
671 results[i].env, results[i].need, results[i].have,
[403b388]672 results[i].openVars };
[a8b27c6]673 newResult.nextArg = nextArg;
[403b388]674 Type* argType;
675
[7faab5e]676 if ( nTuples > 0 || ! results[i].expr ) {
[ad51cc2]677 // first iteration or no expression to clone,
[7faab5e]678 // push empty tuple expression
[403b388]679 newResult.parent = i;
680 std::list<Expression*> emptyList;
681 newResult.expr.reset( new TupleExpr( emptyList ) );
682 argType = newResult.expr->get_result();
[aeb75b1]683 } else {
[403b388]684 // clone result to collect tuple
685 newResult.parent = results[i].parent;
686 newResult.cost = results[i].cost;
687 newResult.tupleStart = results[i].tupleStart;
688 newResult.expr.reset( results[i].expr->clone() );
689 argType = newResult.expr->get_result();
690
691 if ( results[i].tupleStart > 0 && Tuples::isTtype( argType ) ) {
[452747a]692 // the case where a ttype value is passed directly is special,
[403b388]693 // e.g. for argument forwarding purposes
[452747a]694 // xxx - what if passing multiple arguments, last of which is
[403b388]695 // ttype?
[452747a]696 // xxx - what would happen if unify was changed so that unifying
697 // tuple
698 // types flattened both before unifying lists? then pass in
[403b388]699 // TupleType (ttype) below.
700 --newResult.tupleStart;
701 } else {
702 // collapse leftover arguments into tuple
703 newResult.endTuple( results );
704 argType = newResult.expr->get_result();
705 }
[aeb75b1]706 }
[403b388]707
[aeb75b1]708 // check unification for ttype before adding to final
[452747a]709 if ( unify( ttype, argType, newResult.env, newResult.need, newResult.have,
[403b388]710 newResult.openVars, indexer ) ) {
[0bd46fd]711 finalResults.push_back( std::move(newResult) );
[aeb75b1]712 }
[452747a]713
[aeb75b1]714 continue;
715 }
716
717 // add each possible next argument
[a8b27c6]718 for ( std::size_t j = 0; j < args[nextArg].size(); ++j ) {
719 const ExplodedActual& expl = args[nextArg][j];
[178e4ec]720
[403b388]721 // fresh copies of parent parameters for this iteration
722 TypeEnvironment env = results[i].env;
723 OpenVarSet openVars = results[i].openVars;
724
[a8b27c6]725 env.addActual( expl.env, openVars );
[11094d9]726
[a8b27c6]727 // skip empty tuple arguments by (near-)cloning parent into next gen
[62194cb]728 if ( expl.exprs.empty() ) {
[73a5cadb]729 results.emplace_back(
[0bd46fd]730 results[i], std::move(env), copy(results[i].need),
731 copy(results[i].have), std::move(openVars), nextArg + 1, expl.cost );
[452747a]732
[403b388]733 continue;
[4b6ef70]734 }
[11094d9]735
[403b388]736 // add new result
737 results.emplace_back(
[0bd46fd]738 i, expl.exprs.front().get(), std::move(env), copy(results[i].need),
739 copy(results[i].have), std::move(openVars), nextArg + 1,
[62194cb]740 nTuples, expl.cost, expl.exprs.size() == 1 ? 0 : 1, j );
[aeb75b1]741 }
742 }
743
744 // reset for next round
[403b388]745 genStart = genEnd;
746 nTuples = 0;
747 } while ( genEnd != results.size() );
748
749 // splice final results onto results
750 for ( std::size_t i = 0; i < finalResults.size(); ++i ) {
[0bd46fd]751 results.push_back( std::move(finalResults[i]) );
[aeb75b1]752 }
[403b388]753 return ! finalResults.empty();
[aeb75b1]754 }
[11094d9]755
[aeb75b1]756 // iterate each current subresult
[403b388]757 std::size_t genEnd = results.size();
758 for ( std::size_t i = genStart; i < genEnd; ++i ) {
[a8b27c6]759 auto nextArg = results[i].nextArg;
760
[403b388]761 // use remainder of exploded tuple if present
[a8b27c6]762 if ( results[i].hasExpl() ) {
763 const ExplodedActual& expl = results[i].getExpl( args );
[62194cb]764 Expression* expr = expl.exprs[results[i].nextExpl].get();
[452747a]765
[403b388]766 TypeEnvironment env = results[i].env;
767 AssertionSet need = results[i].need, have = results[i].have;
768 OpenVarSet openVars = results[i].openVars;
[4b6ef70]769
[62194cb]770 Type* actualType = expr->get_result();
[4b6ef70]771
772 PRINT(
773 std::cerr << "formal type is ";
774 formalType->print( std::cerr );
775 std::cerr << std::endl << "actual type is ";
776 actualType->print( std::cerr );
777 std::cerr << std::endl;
778 )
[11094d9]779
[403b388]780 if ( unify( formalType, actualType, env, need, have, openVars, indexer ) ) {
[a8b27c6]781 unsigned nextExpl = results[i].nextExpl + 1;
[62194cb]782 if ( nextExpl == expl.exprs.size() ) {
[a8b27c6]783 nextExpl = 0;
784 }
[178e4ec]785
[452747a]786 results.emplace_back(
[0bd46fd]787 i, expr, std::move(env), std::move(need), std::move(have), std::move(openVars), nextArg,
[62194cb]788 nTuples, Cost::zero, nextExpl, results[i].explAlt );
[4b6ef70]789 }
790
791 continue;
[403b388]792 }
[452747a]793
[403b388]794 // use default initializers if out of arguments
[a8b27c6]795 if ( nextArg >= args.size() ) {
[aeb75b1]796 if ( ConstantExpr* cnstExpr = getDefaultValue( initializer ) ) {
797 if ( Constant* cnst = dynamic_cast<Constant*>( cnstExpr->get_constant() ) ) {
[403b388]798 TypeEnvironment env = results[i].env;
799 AssertionSet need = results[i].need, have = results[i].have;
800 OpenVarSet openVars = results[i].openVars;
801
[452747a]802 if ( unify( formalType, cnst->get_type(), env, need, have, openVars,
[403b388]803 indexer ) ) {
804 results.emplace_back(
[0bd46fd]805 i, new DefaultArgExpr( cnstExpr ), std::move(env), std::move(need), std::move(have),
806 std::move(openVars), nextArg, nTuples );
[aeb75b1]807 }
808 }
809 }
[403b388]810
[aeb75b1]811 continue;
812 }
813
814 // Check each possible next argument
[a8b27c6]815 for ( std::size_t j = 0; j < args[nextArg].size(); ++j ) {
816 const ExplodedActual& expl = args[nextArg][j];
817
[403b388]818 // fresh copies of parent parameters for this iteration
819 TypeEnvironment env = results[i].env;
820 AssertionSet need = results[i].need, have = results[i].have;
821 OpenVarSet openVars = results[i].openVars;
822
[a8b27c6]823 env.addActual( expl.env, openVars );
[4b6ef70]824
[a8b27c6]825 // skip empty tuple arguments by (near-)cloning parent into next gen
[62194cb]826 if ( expl.exprs.empty() ) {
[73a5cadb]827 results.emplace_back(
[0bd46fd]828 results[i], std::move(env), std::move(need), std::move(have), std::move(openVars),
[a8b27c6]829 nextArg + 1, expl.cost );
[73a5cadb]830
[4b6ef70]831 continue;
832 }
[aeb75b1]833
[4b6ef70]834 // consider only first exploded actual
[62194cb]835 Expression* expr = expl.exprs.front().get();
[3d2ae8d]836 Type* actualType = expr->result->clone();
[a585396]837
[4b6ef70]838 PRINT(
839 std::cerr << "formal type is ";
840 formalType->print( std::cerr );
841 std::cerr << std::endl << "actual type is ";
842 actualType->print( std::cerr );
843 std::cerr << std::endl;
844 )
[aeb75b1]845
[4b6ef70]846 // attempt to unify types
[403b388]847 if ( unify( formalType, actualType, env, need, have, openVars, indexer ) ) {
848 // add new result
849 results.emplace_back(
[0bd46fd]850 i, expr, std::move(env), std::move(need), std::move(have), std::move(openVars), nextArg + 1,
[62194cb]851 nTuples, expl.cost, expl.exprs.size() == 1 ? 0 : 1, j );
[4b6ef70]852 }
[aeb75b1]853 }
854 }
855
856 // reset for next parameter
[403b388]857 genStart = genEnd;
[11094d9]858
[403b388]859 return genEnd != results.size();
860 }
861
862 template<typename OutputIterator>
[13deae88]863 void AlternativeFinder::Finder::validateFunctionAlternative( const Alternative &func, ArgPack& result,
[403b388]864 const std::vector<ArgPack>& results, OutputIterator out ) {
865 ApplicationExpr *appExpr = new ApplicationExpr( func.expr->clone() );
866 // sum cost and accumulate actuals
[3d2ae8d]867 std::list<Expression*>& args = appExpr->args;
[8a62d04]868 Cost cost = func.cost;
[403b388]869 const ArgPack* pack = &result;
870 while ( pack->expr ) {
871 args.push_front( pack->expr->clone() );
872 cost += pack->cost;
873 pack = &results[pack->parent];
874 }
875 // build and validate new alternative
[2c187378]876 Alternative newAlt{ appExpr, result.env, result.openVars, result.need, cost };
[403b388]877 PRINT(
878 std::cerr << "instantiate function success: " << appExpr << std::endl;
879 std::cerr << "need assertions:" << std::endl;
880 printAssertionSet( result.need, std::cerr, 8 );
881 )
[0b00df0]882 inferParameters( newAlt, out );
[11094d9]883 }
[aeb75b1]884
885 template<typename OutputIterator>
[13deae88]886 void AlternativeFinder::Finder::makeFunctionAlternatives( const Alternative &func,
[432ce7a]887 FunctionType *funcType, const ExplodedArgs_old &args, OutputIterator out ) {
[aeb75b1]888 OpenVarSet funcOpenVars;
889 AssertionSet funcNeed, funcHave;
[3f7e12cb]890 TypeEnvironment funcEnv( func.env );
[aeb75b1]891 makeUnifiableVars( funcType, funcOpenVars, funcNeed );
[11094d9]892 // add all type variables as open variables now so that those not used in the parameter
[aeb75b1]893 // list are still considered open.
[3d2ae8d]894 funcEnv.add( funcType->forall );
[11094d9]895
[3d2ae8d]896 if ( targetType && ! targetType->isVoid() && ! funcType->returnVals.empty() ) {
[ea83e00a]897 // attempt to narrow based on expected target type
[3d2ae8d]898 Type * returnType = funcType->returnVals.front()->get_type();
[11094d9]899 if ( ! unify( returnType, targetType, funcEnv, funcNeed, funcHave, funcOpenVars,
[aeb75b1]900 indexer ) ) {
901 // unification failed, don't pursue this function alternative
[ea83e00a]902 return;
903 }
904 }
905
[aeb75b1]906 // iteratively build matches, one parameter at a time
[403b388]907 std::vector<ArgPack> results;
908 results.push_back( ArgPack{ funcEnv, funcNeed, funcHave, funcOpenVars } );
909 std::size_t genStart = 0;
910
[3d2ae8d]911 for ( DeclarationWithType* formal : funcType->parameters ) {
[aeb75b1]912 ObjectDecl* obj = strict_dynamic_cast< ObjectDecl* >( formal );
[11094d9]913 if ( ! instantiateArgument(
[3d2ae8d]914 obj->type, obj->init, args, results, genStart, indexer ) )
[aeb75b1]915 return;
916 }
917
918 if ( funcType->get_isVarArgs() ) {
[403b388]919 // append any unused arguments to vararg pack
920 std::size_t genEnd;
921 do {
922 genEnd = results.size();
923
924 // iterate results
925 for ( std::size_t i = genStart; i < genEnd; ++i ) {
[a8b27c6]926 auto nextArg = results[i].nextArg;
[452747a]927
[403b388]928 // use remainder of exploded tuple if present
[a8b27c6]929 if ( results[i].hasExpl() ) {
930 const ExplodedActual& expl = results[i].getExpl( args );
[403b388]931
[a8b27c6]932 unsigned nextExpl = results[i].nextExpl + 1;
[62194cb]933 if ( nextExpl == expl.exprs.size() ) {
[a8b27c6]934 nextExpl = 0;
935 }
[403b388]936
937 results.emplace_back(
[178e4ec]938 i, expl.exprs[results[i].nextExpl].get(), copy(results[i].env),
939 copy(results[i].need), copy(results[i].have),
940 copy(results[i].openVars), nextArg, 0, Cost::zero, nextExpl,
[62194cb]941 results[i].explAlt );
[452747a]942
[403b388]943 continue;
944 }
945
946 // finish result when out of arguments
[a8b27c6]947 if ( nextArg >= args.size() ) {
[403b388]948 validateFunctionAlternative( func, results[i], results, out );
[fae6f21]949
[aeb75b1]950 continue;
951 }
952
953 // add each possible next argument
[a8b27c6]954 for ( std::size_t j = 0; j < args[nextArg].size(); ++j ) {
955 const ExplodedActual& expl = args[nextArg][j];
956
[403b388]957 // fresh copies of parent parameters for this iteration
958 TypeEnvironment env = results[i].env;
959 OpenVarSet openVars = results[i].openVars;
960
[a8b27c6]961 env.addActual( expl.env, openVars );
[d551d0a]962
[a8b27c6]963 // skip empty tuple arguments by (near-)cloning parent into next gen
[62194cb]964 if ( expl.exprs.empty() ) {
[452747a]965 results.emplace_back(
[0bd46fd]966 results[i], std::move(env), copy(results[i].need),
967 copy(results[i].have), std::move(openVars), nextArg + 1, expl.cost );
[178e4ec]968
[403b388]969 continue;
970 }
[d551d0a]971
[403b388]972 // add new result
973 results.emplace_back(
[0bd46fd]974 i, expl.exprs.front().get(), std::move(env), copy(results[i].need),
975 copy(results[i].have), std::move(openVars), nextArg + 1, 0,
[62194cb]976 expl.cost, expl.exprs.size() == 1 ? 0 : 1, j );
[aeb75b1]977 }
978 }
979
[403b388]980 genStart = genEnd;
981 } while ( genEnd != results.size() );
[aeb75b1]982 } else {
983 // filter out results that don't use all the arguments
[403b388]984 for ( std::size_t i = genStart; i < results.size(); ++i ) {
985 ArgPack& result = results[i];
[a8b27c6]986 if ( ! result.hasExpl() && result.nextArg >= args.size() ) {
[403b388]987 validateFunctionAlternative( func, result, results, out );
[aeb75b1]988 }
989 }
990 }
[d9a0e76]991 }
992
[13deae88]993 void AlternativeFinder::Finder::postvisit( UntypedExpr *untypedExpr ) {
[6ccfb7f]994 AlternativeFinder funcFinder( indexer, env );
[3d2ae8d]995 funcFinder.findWithAdjustment( untypedExpr->function );
[6ccfb7f]996 // if there are no function alternatives, then proceeding is a waste of time.
[630bcb5]997 // xxx - findWithAdjustment throws, so this check and others like it shouldn't be necessary.
[6ccfb7f]998 if ( funcFinder.alternatives.empty() ) return;
999
[aeb75b1]1000 std::vector< AlternativeFinder > argAlternatives;
[13deae88]1001 altFinder.findSubExprs( untypedExpr->begin_args(), untypedExpr->end_args(),
[aeb75b1]1002 back_inserter( argAlternatives ) );
[d9a0e76]1003
[5af62f1]1004 // take care of possible tuple assignments
1005 // if not tuple assignment, assignment is taken care of as a normal function call
[13deae88]1006 Tuples::handleTupleAssignment( altFinder, untypedExpr, argAlternatives );
[c43c171]1007
[6ccfb7f]1008 // find function operators
[4e66a18]1009 static NameExpr *opExpr = new NameExpr( "?()" );
[6ccfb7f]1010 AlternativeFinder funcOpFinder( indexer, env );
[4e66a18]1011 // it's ok if there aren't any defined function ops
[00ac42e]1012 funcOpFinder.maybeFind( opExpr );
[6ccfb7f]1013 PRINT(
1014 std::cerr << "known function ops:" << std::endl;
[50377a4]1015 printAlts( funcOpFinder.alternatives, std::cerr, 1 );
[6ccfb7f]1016 )
1017
[a8b27c6]1018 // pre-explode arguments
[432ce7a]1019 ExplodedArgs_old argExpansions;
[a8b27c6]1020 argExpansions.reserve( argAlternatives.size() );
1021
1022 for ( const AlternativeFinder& arg : argAlternatives ) {
1023 argExpansions.emplace_back();
1024 auto& argE = argExpansions.back();
[d286cf68]1025 // argE.reserve( arg.alternatives.size() );
[178e4ec]1026
[a8b27c6]1027 for ( const Alternative& actual : arg ) {
1028 argE.emplace_back( actual, indexer );
1029 }
1030 }
1031
[a32b204]1032 AltList candidates;
[a16764a6]1033 SemanticErrorException errors;
[b1bead1]1034 for ( AltList::iterator func = funcFinder.alternatives.begin(); func != funcFinder.alternatives.end(); ++func ) {
[91b8a17]1035 try {
1036 PRINT(
1037 std::cerr << "working on alternative: " << std::endl;
1038 func->print( std::cerr, 8 );
1039 )
1040 // check if the type is pointer to function
[3d2ae8d]1041 if ( PointerType *pointer = dynamic_cast< PointerType* >( func->expr->result->stripReferences() ) ) {
1042 if ( FunctionType *function = dynamic_cast< FunctionType* >( pointer->base ) ) {
[326338ae]1043 Alternative newFunc( *func );
[a181494]1044 referenceToRvalueConversion( newFunc.expr, newFunc.cost );
[a8b27c6]1045 makeFunctionAlternatives( newFunc, function, argExpansions,
[aeb75b1]1046 std::back_inserter( candidates ) );
[b1bead1]1047 }
[3d2ae8d]1048 } else if ( TypeInstType *typeInst = dynamic_cast< TypeInstType* >( func->expr->result->stripReferences() ) ) { // handle ftype (e.g. *? on function pointer)
[00ac42e]1049 if ( const EqvClass *eqvClass = func->env.lookup( typeInst->name ) ) {
1050 if ( FunctionType *function = dynamic_cast< FunctionType* >( eqvClass->type ) ) {
[326338ae]1051 Alternative newFunc( *func );
[a181494]1052 referenceToRvalueConversion( newFunc.expr, newFunc.cost );
[a8b27c6]1053 makeFunctionAlternatives( newFunc, function, argExpansions,
[aeb75b1]1054 std::back_inserter( candidates ) );
[a32b204]1055 } // if
1056 } // if
[11094d9]1057 }
[a16764a6]1058 } catch ( SemanticErrorException &e ) {
[91b8a17]1059 errors.append( e );
1060 }
[a32b204]1061 } // for
1062
[aeb75b1]1063 // try each function operator ?() with each function alternative
1064 if ( ! funcOpFinder.alternatives.empty() ) {
[a8b27c6]1065 // add exploded function alternatives to front of argument list
1066 std::vector<ExplodedActual> funcE;
1067 funcE.reserve( funcFinder.alternatives.size() );
1068 for ( const Alternative& actual : funcFinder ) {
1069 funcE.emplace_back( actual, indexer );
1070 }
[0bd46fd]1071 argExpansions.insert( argExpansions.begin(), std::move(funcE) );
[aeb75b1]1072
1073 for ( AltList::iterator funcOp = funcOpFinder.alternatives.begin();
1074 funcOp != funcOpFinder.alternatives.end(); ++funcOp ) {
1075 try {
1076 // check if type is a pointer to function
[11094d9]1077 if ( PointerType* pointer = dynamic_cast<PointerType*>(
[3d2ae8d]1078 funcOp->expr->result->stripReferences() ) ) {
[11094d9]1079 if ( FunctionType* function =
[3d2ae8d]1080 dynamic_cast<FunctionType*>( pointer->base ) ) {
[aeb75b1]1081 Alternative newFunc( *funcOp );
[a181494]1082 referenceToRvalueConversion( newFunc.expr, newFunc.cost );
[a8b27c6]1083 makeFunctionAlternatives( newFunc, function, argExpansions,
[aeb75b1]1084 std::back_inserter( candidates ) );
1085 }
1086 }
[a16764a6]1087 } catch ( SemanticErrorException &e ) {
[aeb75b1]1088 errors.append( e );
1089 }
1090 }
1091 }
1092
[91b8a17]1093 // Implement SFINAE; resolution errors are only errors if there aren't any non-erroneous resolutions
1094 if ( candidates.empty() && ! errors.isEmpty() ) { throw errors; }
1095
[4b0f997]1096 // compute conversionsion costs
[bd4f2e9]1097 for ( Alternative& withFunc : candidates ) {
1098 Cost cvtCost = computeApplicationConversionCost( withFunc, indexer );
[a32b204]1099
1100 PRINT(
[bd4f2e9]1101 ApplicationExpr *appExpr = strict_dynamic_cast< ApplicationExpr* >( withFunc.expr );
[3d2ae8d]1102 PointerType *pointer = strict_dynamic_cast< PointerType* >( appExpr->function->result );
1103 FunctionType *function = strict_dynamic_cast< FunctionType* >( pointer->base );
1104 std::cerr << "Case +++++++++++++ " << appExpr->function << std::endl;
[6ed1d4b]1105 std::cerr << "formals are:" << std::endl;
[3d2ae8d]1106 printAll( function->parameters, std::cerr, 8 );
[6ed1d4b]1107 std::cerr << "actuals are:" << std::endl;
[3d2ae8d]1108 printAll( appExpr->args, std::cerr, 8 );
[6ed1d4b]1109 std::cerr << "bindings are:" << std::endl;
[bd4f2e9]1110 withFunc.env.print( std::cerr, 8 );
[04cccaf]1111 std::cerr << "cost is: " << withFunc.cost << std::endl;
[6ed1d4b]1112 std::cerr << "cost of conversion is:" << cvtCost << std::endl;
[7c64920]1113 )
1114 if ( cvtCost != Cost::infinity ) {
[bd4f2e9]1115 withFunc.cvtCost = cvtCost;
1116 alternatives.push_back( withFunc );
[7c64920]1117 } // if
[a32b204]1118 } // for
[4b0f997]1119
[0bd46fd]1120 candidates = std::move(alternatives);
[a32b204]1121
[11094d9]1122 // use a new list so that alternatives are not examined by addAnonConversions twice.
1123 AltList winners;
1124 findMinCost( candidates.begin(), candidates.end(), std::back_inserter( winners ) );
[ea83e00a]1125
[452747a]1126 // function may return struct or union value, in which case we need to add alternatives
[73ac10e]1127 // for implicit conversions to each of the anonymous members, must happen after findMinCost
[bd4f2e9]1128 // since anon conversions are never the cheapest expression
[11094d9]1129 for ( const Alternative & alt : winners ) {
[ca946a4]1130 addAnonConversions( alt );
1131 }
[bd4f2e9]1132 spliceBegin( alternatives, winners );
[ca946a4]1133
[ea83e00a]1134 if ( alternatives.empty() && targetType && ! targetType->isVoid() ) {
1135 // xxx - this is a temporary hack. If resolution is unsuccessful with a target type, try again without a
1136 // target type, since it will sometimes succeed when it wouldn't easily with target type binding. For example,
1137 // forall( otype T ) lvalue T ?[?]( T *, ptrdiff_t );
1138 // const char * x = "hello world";
1139 // unsigned char ch = x[0];
1140 // Fails with simple return type binding. First, T is bound to unsigned char, then (x: const char *) is unified
1141 // with unsigned char *, which fails because pointer base types must be unified exactly. The new resolver should
1142 // fix this issue in a more robust way.
1143 targetType = nullptr;
[13deae88]1144 postvisit( untypedExpr );
[ea83e00a]1145 }
[a32b204]1146 }
1147
1148 bool isLvalue( Expression *expr ) {
[906e24d]1149 // xxx - recurse into tuples?
[2d80111]1150 return expr->result && ( expr->get_lvalue() || dynamic_cast< ReferenceType * >( expr->result ) );
[a32b204]1151 }
1152
[13deae88]1153 void AlternativeFinder::Finder::postvisit( AddressExpr *addressExpr ) {
[a32b204]1154 AlternativeFinder finder( indexer, env );
1155 finder.find( addressExpr->get_arg() );
[bd4f2e9]1156 for ( Alternative& alt : finder.alternatives ) {
1157 if ( isLvalue( alt.expr ) ) {
[452747a]1158 alternatives.push_back(
[6d6e829]1159 Alternative{ alt, new AddressExpr( alt.expr->clone() ), alt.cost } );
[a32b204]1160 } // if
1161 } // for
1162 }
1163
[13deae88]1164 void AlternativeFinder::Finder::postvisit( LabelAddressExpr * expr ) {
[6d6e829]1165 alternatives.push_back( Alternative{ expr->clone(), env } );
[5809461]1166 }
1167
[c0bf94e]1168 Expression * restructureCast( Expression * argExpr, Type * toType, bool isGenerated ) {
[e6cee92]1169 if ( argExpr->get_result()->size() > 1 && ! toType->isVoid() && ! dynamic_cast<ReferenceType *>( toType ) ) {
1170 // Argument expression is a tuple and the target type is not void and not a reference type.
1171 // Cast each member of the tuple to its corresponding target type, producing the tuple of those
1172 // cast expressions. If there are more components of the tuple than components in the target type,
1173 // then excess components do not come out in the result expression (but UniqueExprs ensure that
1174 // side effects will still be done).
[5ccb10d]1175 if ( Tuples::maybeImpureIgnoreUnique( argExpr ) ) {
[62423350]1176 // expressions which may contain side effects require a single unique instance of the expression.
1177 argExpr = new UniqueExpr( argExpr );
1178 }
1179 std::list< Expression * > componentExprs;
1180 for ( unsigned int i = 0; i < toType->size(); i++ ) {
1181 // cast each component
1182 TupleIndexExpr * idx = new TupleIndexExpr( argExpr->clone(), i );
[c0bf94e]1183 componentExprs.push_back( restructureCast( idx, toType->getComponent( i ), isGenerated ) );
[62423350]1184 }
1185 delete argExpr;
1186 assert( componentExprs.size() > 0 );
1187 // produce the tuple of casts
1188 return new TupleExpr( componentExprs );
1189 } else {
1190 // handle normally
[c0bf94e]1191 CastExpr * ret = new CastExpr( argExpr, toType->clone() );
1192 ret->isGenerated = isGenerated;
1193 return ret;
[62423350]1194 }
1195 }
1196
[13deae88]1197 void AlternativeFinder::Finder::postvisit( CastExpr *castExpr ) {
[906e24d]1198 Type *& toType = castExpr->get_result();
[7933351]1199 assert( toType );
[906e24d]1200 toType = resolveTypeof( toType, indexer );
[cc4218f]1201 assert(!dynamic_cast<TypeofType *>(toType));
[906e24d]1202 SymTab::validateType( toType, &indexer );
1203 adjustExprType( toType, env, indexer );
[a32b204]1204
1205 AlternativeFinder finder( indexer, env );
[7933351]1206 finder.targetType = toType;
[95642c9]1207 finder.findWithAdjustment( castExpr->arg );
[a32b204]1208
1209 AltList candidates;
[452747a]1210 for ( Alternative & alt : finder.alternatives ) {
[6d6e829]1211 AssertionSet needAssertions( alt.need.begin(), alt.need.end() );
1212 AssertionSet haveAssertions;
1213 OpenVarSet openVars{ alt.openVars };
[a32b204]1214
[a8706fc]1215 alt.env.extractOpenVars( openVars );
1216
[a32b204]1217 // It's possible that a cast can throw away some values in a multiply-valued expression. (An example is a
1218 // cast-to-void, which casts from one value to zero.) Figure out the prefix of the subexpression results
1219 // that are cast directly. The candidate is invalid if it has fewer results than there are types to cast
1220 // to.
[95642c9]1221 int discardedValues = alt.expr->result->size() - castExpr->result->size();
[a32b204]1222 if ( discardedValues < 0 ) continue;
[7933351]1223 // xxx - may need to go into tuple types and extract relevant types and use unifyList. Note that currently, this does not
1224 // allow casting a tuple to an atomic type (e.g. (int)([1, 2, 3]))
[adcdd2f]1225 // unification run for side-effects
[95642c9]1226 unify( castExpr->result, alt.expr->result, alt.env, needAssertions,
[bd4f2e9]1227 haveAssertions, openVars, indexer );
[b81fd95]1228 Cost thisCost =
1229 castExpr->isGenerated
1230 ? conversionCost( alt.expr->result, castExpr->result, alt.expr->get_lvalue(), indexer, alt.env )
1231 : castCost( alt.expr->result, castExpr->result, alt.expr->get_lvalue(), indexer, alt.env );
[7e4c4f4]1232 PRINT(
1233 std::cerr << "working on cast with result: " << castExpr->result << std::endl;
[452747a]1234 std::cerr << "and expr type: " << alt.expr->result << std::endl;
1235 std::cerr << "env: " << alt.env << std::endl;
[7e4c4f4]1236 )
[a32b204]1237 if ( thisCost != Cost::infinity ) {
[7e4c4f4]1238 PRINT(
1239 std::cerr << "has finite cost." << std::endl;
1240 )
[a32b204]1241 // count one safe conversion for each value that is thrown away
[89be1c68]1242 thisCost.incSafe( discardedValues );
[6f096d2]1243 Alternative newAlt{
1244 restructureCast( alt.expr->clone(), toType, castExpr->isGenerated ),
[bd78797]1245 alt.env, openVars, needAssertions, alt.cost, alt.cost + thisCost };
[0b00df0]1246 inferParameters( newAlt, back_inserter( candidates ) );
[a32b204]1247 } // if
1248 } // for
1249
1250 // findMinCost selects the alternatives with the lowest "cost" members, but has the side effect of copying the
1251 // cvtCost member to the cost member (since the old cost is now irrelevant). Thus, calling findMinCost twice
1252 // selects first based on argument cost, then on conversion cost.
1253 AltList minArgCost;
1254 findMinCost( candidates.begin(), candidates.end(), std::back_inserter( minArgCost ) );
1255 findMinCost( minArgCost.begin(), minArgCost.end(), std::back_inserter( alternatives ) );
1256 }
1257
[13deae88]1258 void AlternativeFinder::Finder::postvisit( VirtualCastExpr * castExpr ) {
[6d6e829]1259 assertf( castExpr->get_result(), "Implicit virtual cast targets not yet supported." );
[a5f0529]1260 AlternativeFinder finder( indexer, env );
1261 // don't prune here, since it's guaranteed all alternatives will have the same type
[4e66a18]1262 finder.findWithoutPrune( castExpr->get_arg() );
[a5f0529]1263 for ( Alternative & alt : finder.alternatives ) {
[6d6e829]1264 alternatives.push_back( Alternative{
1265 alt, new VirtualCastExpr{ alt.expr->clone(), castExpr->get_result()->clone() },
1266 alt.cost } );
[a5f0529]1267 }
1268 }
1269
[3b0c8cb]1270 void AlternativeFinder::Finder::postvisit( KeywordCastExpr * castExpr ) {
1271 assertf( castExpr->get_result(), "Cast target should have been set in Validate." );
1272 auto ref = dynamic_cast<ReferenceType*>(castExpr->get_result());
1273 assert(ref);
1274 auto inst = dynamic_cast<StructInstType*>(ref->base);
1275 assert(inst);
1276 auto target = inst->baseStruct;
1277
1278 AlternativeFinder finder( indexer, env );
1279
1280 auto pick_alternatives = [target, this](AltList & found, bool expect_ref) {
1281 for(auto & alt : found) {
1282 Type * expr = alt.expr->get_result();
1283 if(expect_ref) {
1284 auto res = dynamic_cast<ReferenceType*>(expr);
1285 if(!res) { continue; }
1286 expr = res->base;
1287 }
1288
1289 if(auto insttype = dynamic_cast<TypeInstType*>(expr)) {
1290 auto td = alt.env.lookup(insttype->name);
1291 if(!td) { continue; }
1292 expr = td->type;
1293 }
1294
1295 if(auto base = dynamic_cast<StructInstType*>(expr)) {
1296 if(base->baseStruct == target) {
1297 alternatives.push_back(
1298 std::move(alt)
1299 );
1300 }
1301 }
1302 }
1303 };
1304
1305 try {
[7f62b708]1306 // Attempt 1 : turn (thread&)X into (thread$&)X.__thrd
[3b0c8cb]1307 // Clone is purely for memory management
1308 std::unique_ptr<Expression> tech1 { new UntypedMemberExpr(new NameExpr(castExpr->concrete_target.field), castExpr->arg->clone()) };
1309
1310 // don't prune here, since it's guaranteed all alternatives will have the same type
1311 finder.findWithoutPrune( tech1.get() );
1312 pick_alternatives(finder.alternatives, false);
1313
1314 return;
1315 } catch(SemanticErrorException & ) {}
1316
[7f62b708]1317 // Fallback : turn (thread&)X into (thread$&)get_thread(X)
[3b0c8cb]1318 std::unique_ptr<Expression> fallback { UntypedExpr::createDeref( new UntypedExpr(new NameExpr(castExpr->concrete_target.getter), { castExpr->arg->clone() })) };
1319 // don't prune here, since it's guaranteed all alternatives will have the same type
1320 finder.findWithoutPrune( fallback.get() );
1321
1322 pick_alternatives(finder.alternatives, true);
1323
1324 // Whatever happens here, we have no more fallbacks
1325 }
1326
[00ac42e]1327 namespace {
1328 /// Gets name from untyped member expression (member must be NameExpr)
1329 const std::string& get_member_name( UntypedMemberExpr *memberExpr ) {
[30ee9efc]1330 if ( dynamic_cast< ConstantExpr * >( memberExpr->get_member() ) ) {
1331 SemanticError( memberExpr, "Indexed access to struct fields unsupported: " );
1332 } // if
[00ac42e]1333 NameExpr * nameExpr = dynamic_cast< NameExpr * >( memberExpr->get_member() );
1334 assert( nameExpr );
1335 return nameExpr->get_name();
1336 }
1337 }
1338
[13deae88]1339 void AlternativeFinder::Finder::postvisit( UntypedMemberExpr *memberExpr ) {
[a32b204]1340 AlternativeFinder funcFinder( indexer, env );
1341 funcFinder.findWithAdjustment( memberExpr->get_aggregate() );
1342 for ( AltList::const_iterator agg = funcFinder.alternatives.begin(); agg != funcFinder.alternatives.end(); ++agg ) {
[a61ad31]1343 // it's okay for the aggregate expression to have reference type -- cast it to the base type to treat the aggregate as the referenced value
[a181494]1344 Cost cost = agg->cost;
1345 Expression * aggrExpr = agg->expr->clone();
1346 referenceToRvalueConversion( aggrExpr, cost );
1347 std::unique_ptr<Expression> guard( aggrExpr );
1348
[a61ad31]1349 // find member of the given type
1350 if ( StructInstType *structInst = dynamic_cast< StructInstType* >( aggrExpr->get_result() ) ) {
[6d6e829]1351 addAggMembers( structInst, aggrExpr, *agg, cost, get_member_name(memberExpr) );
[a61ad31]1352 } else if ( UnionInstType *unionInst = dynamic_cast< UnionInstType* >( aggrExpr->get_result() ) ) {
[6d6e829]1353 addAggMembers( unionInst, aggrExpr, *agg, cost, get_member_name(memberExpr) );
[a61ad31]1354 } else if ( TupleType * tupleType = dynamic_cast< TupleType * >( aggrExpr->get_result() ) ) {
[6d6e829]1355 addTupleMembers( tupleType, aggrExpr, *agg, cost, memberExpr->get_member() );
[a32b204]1356 } // if
1357 } // for
1358 }
1359
[13deae88]1360 void AlternativeFinder::Finder::postvisit( MemberExpr *memberExpr ) {
[6d6e829]1361 alternatives.push_back( Alternative{ memberExpr->clone(), env } );
[a32b204]1362 }
1363
[13deae88]1364 void AlternativeFinder::Finder::postvisit( NameExpr *nameExpr ) {
[a40d503]1365 std::list< SymTab::Indexer::IdData > declList;
[490ff5c3]1366 indexer.lookupId( nameExpr->name, declList );
1367 PRINT( std::cerr << "nameExpr is " << nameExpr->name << std::endl; )
[a40d503]1368 for ( auto & data : declList ) {
[a181494]1369 Cost cost = Cost::zero;
1370 Expression * newExpr = data.combine( cost );
[5de1e2c]1371
1372 // addAnonAlternatives uses vector::push_back, which invalidates references to existing elements, so
1373 // can't construct in place and use vector::back
[6d6e829]1374 Alternative newAlt{ newExpr, env, OpenVarSet{}, AssertionList{}, Cost::zero, cost };
[0f19d763]1375 PRINT(
1376 std::cerr << "decl is ";
[a40d503]1377 data.id->print( std::cerr );
[0f19d763]1378 std::cerr << std::endl;
1379 std::cerr << "newExpr is ";
[a40d503]1380 newExpr->print( std::cerr );
[0f19d763]1381 std::cerr << std::endl;
[7c64920]1382 )
[5de1e2c]1383 renameTypes( newAlt.expr );
1384 addAnonConversions( newAlt ); // add anonymous member interpretations whenever an aggregate value type is seen as a name expression.
1385 alternatives.push_back( std::move(newAlt) );
[0f19d763]1386 } // for
[a32b204]1387 }
1388
[13deae88]1389 void AlternativeFinder::Finder::postvisit( VariableExpr *variableExpr ) {
[85517ddb]1390 // not sufficient to clone here, because variable's type may have changed
1391 // since the VariableExpr was originally created.
[6d6e829]1392 alternatives.push_back( Alternative{ new VariableExpr{ variableExpr->var }, env } );
[a32b204]1393 }
1394
[13deae88]1395 void AlternativeFinder::Finder::postvisit( ConstantExpr *constantExpr ) {
[6d6e829]1396 alternatives.push_back( Alternative{ constantExpr->clone(), env } );
[a32b204]1397 }
1398
[13deae88]1399 void AlternativeFinder::Finder::postvisit( SizeofExpr *sizeofExpr ) {
[a32b204]1400 if ( sizeofExpr->get_isType() ) {
[322b97e]1401 Type * newType = sizeofExpr->get_type()->clone();
[6f096d2]1402 alternatives.push_back( Alternative{
[6d6e829]1403 new SizeofExpr{ resolveTypeof( newType, indexer ) }, env } );
[a32b204]1404 } else {
1405 // find all alternatives for the argument to sizeof
1406 AlternativeFinder finder( indexer, env );
1407 finder.find( sizeofExpr->get_expr() );
1408 // find the lowest cost alternative among the alternatives, otherwise ambiguous
1409 AltList winners;
1410 findMinCost( finder.alternatives.begin(), finder.alternatives.end(), back_inserter( winners ) );
1411 if ( winners.size() != 1 ) {
[a16764a6]1412 SemanticError( sizeofExpr->get_expr(), "Ambiguous expression in sizeof operand: " );
[a32b204]1413 } // if
1414 // return the lowest cost alternative for the argument
1415 Alternative &choice = winners.front();
[a181494]1416 referenceToRvalueConversion( choice.expr, choice.cost );
[6f096d2]1417 alternatives.push_back( Alternative{
[6d6e829]1418 choice, new SizeofExpr( choice.expr->clone() ), Cost::zero } );
[47534159]1419 } // if
1420 }
1421
[13deae88]1422 void AlternativeFinder::Finder::postvisit( AlignofExpr *alignofExpr ) {
[47534159]1423 if ( alignofExpr->get_isType() ) {
[322b97e]1424 Type * newType = alignofExpr->get_type()->clone();
[6f096d2]1425 alternatives.push_back( Alternative{
[6d6e829]1426 new AlignofExpr{ resolveTypeof( newType, indexer ) }, env } );
[47534159]1427 } else {
1428 // find all alternatives for the argument to sizeof
1429 AlternativeFinder finder( indexer, env );
1430 finder.find( alignofExpr->get_expr() );
1431 // find the lowest cost alternative among the alternatives, otherwise ambiguous
1432 AltList winners;
1433 findMinCost( finder.alternatives.begin(), finder.alternatives.end(), back_inserter( winners ) );
1434 if ( winners.size() != 1 ) {
[a16764a6]1435 SemanticError( alignofExpr->get_expr(), "Ambiguous expression in alignof operand: " );
[47534159]1436 } // if
1437 // return the lowest cost alternative for the argument
1438 Alternative &choice = winners.front();
[a181494]1439 referenceToRvalueConversion( choice.expr, choice.cost );
[6f096d2]1440 alternatives.push_back( Alternative{
[6d6e829]1441 choice, new AlignofExpr{ choice.expr->clone() }, Cost::zero } );
[a32b204]1442 } // if
1443 }
1444
[2a4b088]1445 template< typename StructOrUnionType >
[13deae88]1446 void AlternativeFinder::Finder::addOffsetof( StructOrUnionType *aggInst, const std::string &name ) {
[2a4b088]1447 std::list< Declaration* > members;
1448 aggInst->lookup( name, members );
1449 for ( std::list< Declaration* >::const_iterator i = members.begin(); i != members.end(); ++i ) {
1450 if ( DeclarationWithType *dwt = dynamic_cast< DeclarationWithType* >( *i ) ) {
[6f096d2]1451 alternatives.push_back( Alternative{
[6d6e829]1452 new OffsetofExpr{ aggInst->clone(), dwt }, env } );
[2a4b088]1453 renameTypes( alternatives.back().expr );
1454 } else {
1455 assert( false );
1456 }
1457 }
1458 }
[6ed1d4b]1459
[13deae88]1460 void AlternativeFinder::Finder::postvisit( UntypedOffsetofExpr *offsetofExpr ) {
[2a4b088]1461 AlternativeFinder funcFinder( indexer, env );
[85517ddb]1462 // xxx - resolveTypeof?
[2a4b088]1463 if ( StructInstType *structInst = dynamic_cast< StructInstType* >( offsetofExpr->get_type() ) ) {
[490ff5c3]1464 addOffsetof( structInst, offsetofExpr->member );
[2a4b088]1465 } else if ( UnionInstType *unionInst = dynamic_cast< UnionInstType* >( offsetofExpr->get_type() ) ) {
[490ff5c3]1466 addOffsetof( unionInst, offsetofExpr->member );
[2a4b088]1467 }
1468 }
[6ed1d4b]1469
[13deae88]1470 void AlternativeFinder::Finder::postvisit( OffsetofExpr *offsetofExpr ) {
[6d6e829]1471 alternatives.push_back( Alternative{ offsetofExpr->clone(), env } );
[afc1045]1472 }
1473
[13deae88]1474 void AlternativeFinder::Finder::postvisit( OffsetPackExpr *offsetPackExpr ) {
[6d6e829]1475 alternatives.push_back( Alternative{ offsetPackExpr->clone(), env } );
[25a054f]1476 }
1477
[6f096d2]1478 void AlternativeFinder::Finder::postvisit( LogicalExpr * logicalExpr ) {
[a32b204]1479 AlternativeFinder firstFinder( indexer, env );
1480 firstFinder.findWithAdjustment( logicalExpr->get_arg1() );
[fee651f]1481 if ( firstFinder.alternatives.empty() ) return;
1482 AlternativeFinder secondFinder( indexer, env );
1483 secondFinder.findWithAdjustment( logicalExpr->get_arg2() );
1484 if ( secondFinder.alternatives.empty() ) return;
[490ff5c3]1485 for ( const Alternative & first : firstFinder.alternatives ) {
1486 for ( const Alternative & second : secondFinder.alternatives ) {
[6d6e829]1487 TypeEnvironment compositeEnv{ first.env };
[490ff5c3]1488 compositeEnv.simpleCombine( second.env );
[6d6e829]1489 OpenVarSet openVars{ first.openVars };
1490 mergeOpenVars( openVars, second.openVars );
[2c187378]1491 AssertionSet need;
1492 cloneAll( first.need, need );
1493 cloneAll( second.need, need );
[6d6e829]1494
[6f096d2]1495 LogicalExpr *newExpr = new LogicalExpr{
[6d6e829]1496 first.expr->clone(), second.expr->clone(), logicalExpr->get_isAnd() };
[6f096d2]1497 alternatives.push_back( Alternative{
1498 newExpr, std::move(compositeEnv), std::move(openVars),
[2c187378]1499 AssertionList( need.begin(), need.end() ), first.cost + second.cost } );
[d9a0e76]1500 }
1501 }
1502 }
[51b73452]1503
[13deae88]1504 void AlternativeFinder::Finder::postvisit( ConditionalExpr *conditionalExpr ) {
[32b8144]1505 // find alternatives for condition
[a32b204]1506 AlternativeFinder firstFinder( indexer, env );
[624b722d]1507 firstFinder.findWithAdjustment( conditionalExpr->arg1 );
[ebcb7ba]1508 if ( firstFinder.alternatives.empty() ) return;
1509 // find alternatives for true expression
1510 AlternativeFinder secondFinder( indexer, env );
[624b722d]1511 secondFinder.findWithAdjustment( conditionalExpr->arg2 );
[ebcb7ba]1512 if ( secondFinder.alternatives.empty() ) return;
1513 // find alterantives for false expression
1514 AlternativeFinder thirdFinder( indexer, env );
[624b722d]1515 thirdFinder.findWithAdjustment( conditionalExpr->arg3 );
[ebcb7ba]1516 if ( thirdFinder.alternatives.empty() ) return;
[624b722d]1517 for ( const Alternative & first : firstFinder.alternatives ) {
1518 for ( const Alternative & second : secondFinder.alternatives ) {
1519 for ( const Alternative & third : thirdFinder.alternatives ) {
[6d6e829]1520 TypeEnvironment compositeEnv{ first.env };
[624b722d]1521 compositeEnv.simpleCombine( second.env );
1522 compositeEnv.simpleCombine( third.env );
[6d6e829]1523 OpenVarSet openVars{ first.openVars };
1524 mergeOpenVars( openVars, second.openVars );
1525 mergeOpenVars( openVars, third.openVars );
[2c187378]1526 AssertionSet need;
1527 cloneAll( first.need, need );
1528 cloneAll( second.need, need );
1529 cloneAll( third.need, need );
1530 AssertionSet have;
[6f096d2]1531
[32b8144]1532 // unify true and false types, then infer parameters to produce new alternatives
[668e971a]1533 Type* commonType = nullptr;
[6f096d2]1534 if ( unify( second.expr->result, third.expr->result, compositeEnv,
[2c187378]1535 need, have, openVars, indexer, commonType ) ) {
[6f096d2]1536 ConditionalExpr *newExpr = new ConditionalExpr{
[6d6e829]1537 first.expr->clone(), second.expr->clone(), third.expr->clone() };
[624b722d]1538 newExpr->result = commonType ? commonType : second.expr->result->clone();
[ddf8a29]1539 // convert both options to the conditional result type
[6d6e829]1540 Cost cost = first.cost + second.cost + third.cost;
[6f096d2]1541 cost += computeExpressionConversionCost(
[6d6e829]1542 newExpr->arg2, newExpr->result, indexer, compositeEnv );
[6f096d2]1543 cost += computeExpressionConversionCost(
[6d6e829]1544 newExpr->arg3, newExpr->result, indexer, compositeEnv );
1545 // output alternative
[6f096d2]1546 Alternative newAlt{
1547 newExpr, std::move(compositeEnv), std::move(openVars),
[2c187378]1548 AssertionList( need.begin(), need.end() ), cost };
[0b00df0]1549 inferParameters( newAlt, back_inserter( alternatives ) );
[a32b204]1550 } // if
1551 } // for
1552 } // for
1553 } // for
1554 }
1555
[13deae88]1556 void AlternativeFinder::Finder::postvisit( CommaExpr *commaExpr ) {
[a32b204]1557 TypeEnvironment newEnv( env );
1558 Expression *newFirstArg = resolveInVoidContext( commaExpr->get_arg1(), indexer, newEnv );
1559 AlternativeFinder secondFinder( indexer, newEnv );
1560 secondFinder.findWithAdjustment( commaExpr->get_arg2() );
[490ff5c3]1561 for ( const Alternative & alt : secondFinder.alternatives ) {
[6f096d2]1562 alternatives.push_back( Alternative{
[6d6e829]1563 alt, new CommaExpr{ newFirstArg->clone(), alt.expr->clone() }, alt.cost } );
[a32b204]1564 } // for
1565 delete newFirstArg;
1566 }
1567
[13deae88]1568 void AlternativeFinder::Finder::postvisit( RangeExpr * rangeExpr ) {
[32b8144]1569 // resolve low and high, accept alternatives whose low and high types unify
1570 AlternativeFinder firstFinder( indexer, env );
[490ff5c3]1571 firstFinder.findWithAdjustment( rangeExpr->low );
[fee651f]1572 if ( firstFinder.alternatives.empty() ) return;
1573 AlternativeFinder secondFinder( indexer, env );
[490ff5c3]1574 secondFinder.findWithAdjustment( rangeExpr->high );
[fee651f]1575 if ( secondFinder.alternatives.empty() ) return;
[490ff5c3]1576 for ( const Alternative & first : firstFinder.alternatives ) {
1577 for ( const Alternative & second : secondFinder.alternatives ) {
[6d6e829]1578 TypeEnvironment compositeEnv{ first.env };
[490ff5c3]1579 compositeEnv.simpleCombine( second.env );
[6d6e829]1580 OpenVarSet openVars{ first.openVars };
1581 mergeOpenVars( openVars, second.openVars );
[2c187378]1582 AssertionSet need;
1583 cloneAll( first.need, need );
1584 cloneAll( second.need, need );
1585 AssertionSet have;
[6d6e829]1586
[32b8144]1587 Type* commonType = nullptr;
[6f096d2]1588 if ( unify( first.expr->result, second.expr->result, compositeEnv, need, have,
[2c187378]1589 openVars, indexer, commonType ) ) {
[6f096d2]1590 RangeExpr * newExpr =
[6d6e829]1591 new RangeExpr{ first.expr->clone(), second.expr->clone() };
[490ff5c3]1592 newExpr->result = commonType ? commonType : first.expr->result->clone();
[6f096d2]1593 Alternative newAlt{
1594 newExpr, std::move(compositeEnv), std::move(openVars),
[2c187378]1595 AssertionList( need.begin(), need.end() ), first.cost + second.cost };
[0b00df0]1596 inferParameters( newAlt, back_inserter( alternatives ) );
[32b8144]1597 } // if
1598 } // for
1599 } // for
1600 }
1601
[13deae88]1602 void AlternativeFinder::Finder::postvisit( UntypedTupleExpr *tupleExpr ) {
[bd4f2e9]1603 std::vector< AlternativeFinder > subExprAlternatives;
[13deae88]1604 altFinder.findSubExprs( tupleExpr->get_exprs().begin(), tupleExpr->get_exprs().end(),
[bd4f2e9]1605 back_inserter( subExprAlternatives ) );
1606 std::vector< AltList > possibilities;
[452747a]1607 combos( subExprAlternatives.begin(), subExprAlternatives.end(),
[bd4f2e9]1608 back_inserter( possibilities ) );
1609 for ( const AltList& alts : possibilities ) {
[907eccb]1610 std::list< Expression * > exprs;
[bd4f2e9]1611 makeExprList( alts, exprs );
[a32b204]1612
1613 TypeEnvironment compositeEnv;
[6d6e829]1614 OpenVarSet openVars;
1615 AssertionSet need;
1616 for ( const Alternative& alt : alts ) {
1617 compositeEnv.simpleCombine( alt.env );
1618 mergeOpenVars( openVars, alt.openVars );
[2c187378]1619 cloneAll( alt.need, need );
[6d6e829]1620 }
[6f096d2]1621
1622 alternatives.push_back( Alternative{
1623 new TupleExpr{ exprs }, std::move(compositeEnv), std::move(openVars),
[6d6e829]1624 AssertionList( need.begin(), need.end() ), sumCost( alts ) } );
[a32b204]1625 } // for
[d9a0e76]1626 }
[dc2e7e0]1627
[13deae88]1628 void AlternativeFinder::Finder::postvisit( TupleExpr *tupleExpr ) {
[6d6e829]1629 alternatives.push_back( Alternative{ tupleExpr->clone(), env } );
[907eccb]1630 }
1631
[13deae88]1632 void AlternativeFinder::Finder::postvisit( ImplicitCopyCtorExpr * impCpCtorExpr ) {
[6d6e829]1633 alternatives.push_back( Alternative{ impCpCtorExpr->clone(), env } );
[dc2e7e0]1634 }
[b6fe7e6]1635
[13deae88]1636 void AlternativeFinder::Finder::postvisit( ConstructorExpr * ctorExpr ) {
[b6fe7e6]1637 AlternativeFinder finder( indexer, env );
1638 // don't prune here, since it's guaranteed all alternatives will have the same type
1639 // (giving the alternatives different types is half of the point of ConstructorExpr nodes)
[4e66a18]1640 finder.findWithoutPrune( ctorExpr->get_callExpr() );
[b6fe7e6]1641 for ( Alternative & alt : finder.alternatives ) {
[6f096d2]1642 alternatives.push_back( Alternative{
[6d6e829]1643 alt, new ConstructorExpr( alt.expr->clone() ), alt.cost } );
[b6fe7e6]1644 }
1645 }
[8f7cea1]1646
[13deae88]1647 void AlternativeFinder::Finder::postvisit( TupleIndexExpr *tupleExpr ) {
[6d6e829]1648 alternatives.push_back( Alternative{ tupleExpr->clone(), env } );
[8f7cea1]1649 }
[aa8f9df]1650
[13deae88]1651 void AlternativeFinder::Finder::postvisit( TupleAssignExpr *tupleAssignExpr ) {
[6d6e829]1652 alternatives.push_back( Alternative{ tupleAssignExpr->clone(), env } );
[aa8f9df]1653 }
[bf32bb8]1654
[13deae88]1655 void AlternativeFinder::Finder::postvisit( UniqueExpr *unqExpr ) {
[bf32bb8]1656 AlternativeFinder finder( indexer, env );
1657 finder.findWithAdjustment( unqExpr->get_expr() );
1658 for ( Alternative & alt : finder.alternatives ) {
[141b786]1659 // ensure that the id is passed on to the UniqueExpr alternative so that the expressions are "linked"
[77971f6]1660 UniqueExpr * newUnqExpr = new UniqueExpr( alt.expr->clone(), unqExpr->get_id() );
[6d6e829]1661 alternatives.push_back( Alternative{ alt, newUnqExpr, alt.cost } );
[bf32bb8]1662 }
1663 }
1664
[13deae88]1665 void AlternativeFinder::Finder::postvisit( StmtExpr *stmtExpr ) {
[722617d]1666 StmtExpr * newStmtExpr = stmtExpr->clone();
1667 ResolvExpr::resolveStmtExpr( newStmtExpr, indexer );
1668 // xxx - this env is almost certainly wrong, and needs to somehow contain the combined environments from all of the statements in the stmtExpr...
[6d6e829]1669 alternatives.push_back( Alternative{ newStmtExpr, env } );
[722617d]1670 }
1671
[13deae88]1672 void AlternativeFinder::Finder::postvisit( UntypedInitExpr *initExpr ) {
[62423350]1673 // handle each option like a cast
[e4d829b]1674 AltList candidates;
[13deae88]1675 PRINT(
1676 std::cerr << "untyped init expr: " << initExpr << std::endl;
1677 )
[e4d829b]1678 // O(N^2) checks of d-types with e-types
[62423350]1679 for ( InitAlternative & initAlt : initExpr->get_initAlts() ) {
[228099e]1680 Type * toType = resolveTypeof( initAlt.type->clone(), indexer );
[62423350]1681 SymTab::validateType( toType, &indexer );
1682 adjustExprType( toType, env, indexer );
1683 // Ideally the call to findWithAdjustment could be moved out of the loop, but unfortunately it currently has to occur inside or else
1684 // polymorphic return types are not properly bound to the initialization type, since return type variables are only open for the duration of resolving
1685 // the UntypedExpr. This is only actually an issue in initialization contexts that allow more than one possible initialization type, but it is still suboptimal.
1686 AlternativeFinder finder( indexer, env );
1687 finder.targetType = toType;
[3d2ae8d]1688 finder.findWithAdjustment( initExpr->expr );
[62423350]1689 for ( Alternative & alt : finder.get_alternatives() ) {
1690 TypeEnvironment newEnv( alt.env );
[2c187378]1691 AssertionSet need;
1692 cloneAll( alt.need, need );
1693 AssertionSet have;
[6f096d2]1694 OpenVarSet openVars( alt.openVars );
1695 // xxx - find things in env that don't have a "representative type" and claim
[6d6e829]1696 // those are open vars?
[13deae88]1697 PRINT(
1698 std::cerr << " @ " << toType << " " << initAlt.designation << std::endl;
[3d2ae8d]1699 )
[6f096d2]1700 // It's possible that a cast can throw away some values in a multiply-valued
1701 // expression. (An example is a cast-to-void, which casts from one value to
1702 // zero.) Figure out the prefix of the subexpression results that are cast
1703 // directly. The candidate is invalid if it has fewer results than there are
[6d6e829]1704 // types to cast to.
[3d2ae8d]1705 int discardedValues = alt.expr->result->size() - toType->size();
[e4d829b]1706 if ( discardedValues < 0 ) continue;
[6f096d2]1707 // xxx - may need to go into tuple types and extract relevant types and use
1708 // unifyList. Note that currently, this does not allow casting a tuple to an
[6d6e829]1709 // atomic type (e.g. (int)([1, 2, 3]))
[6f096d2]1710
[e4d829b]1711 // unification run for side-effects
[b81fd95]1712 bool canUnify = unify( toType, alt.expr->result, newEnv, need, have, openVars, indexer );
1713 (void) canUnify;
[6d6e829]1714 // xxx - do some inspecting on this line... why isn't result bound to initAlt.type?
[e4d829b]1715
[b81fd95]1716 Cost thisCost = computeConversionCost( alt.expr->result, toType, alt.expr->get_lvalue(),
[7d01cf44]1717 indexer, newEnv );
[b81fd95]1718
1719 PRINT(
1720 Cost legacyCost = castCost( alt.expr->result, toType, alt.expr->get_lvalue(),
1721 indexer, newEnv );
1722 std::cerr << "Considering initialization:";
1723 std::cerr << std::endl << " FROM: "; alt.expr->result->print(std::cerr);
1724 std::cerr << std::endl << " TO: "; toType ->print(std::cerr);
1725 std::cerr << std::endl << " Unification " << (canUnify ? "succeeded" : "failed");
1726 std::cerr << std::endl << " Legacy cost " << legacyCost;
1727 std::cerr << std::endl << " New cost " << thisCost;
1728 std::cerr << std::endl;
1729 )
[1db306a]1730
[e4d829b]1731 if ( thisCost != Cost::infinity ) {
1732 // count one safe conversion for each value that is thrown away
[89be1c68]1733 thisCost.incSafe( discardedValues );
[6f096d2]1734 Alternative newAlt{
1735 new InitExpr{
1736 restructureCast( alt.expr->clone(), toType, true ), initAlt.designation->clone() },
1737 std::move(newEnv), std::move(openVars),
[2c187378]1738 AssertionList( need.begin(), need.end() ), alt.cost, thisCost };
[0b00df0]1739 inferParameters( newAlt, back_inserter( candidates ) );
[e4d829b]1740 }
1741 }
1742 }
1743
1744 // findMinCost selects the alternatives with the lowest "cost" members, but has the side effect of copying the
1745 // cvtCost member to the cost member (since the old cost is now irrelevant). Thus, calling findMinCost twice
1746 // selects first based on argument cost, then on conversion cost.
1747 AltList minArgCost;
1748 findMinCost( candidates.begin(), candidates.end(), std::back_inserter( minArgCost ) );
1749 findMinCost( minArgCost.begin(), minArgCost.end(), std::back_inserter( alternatives ) );
1750 }
[c71b256]1751
1752 void AlternativeFinder::Finder::postvisit( InitExpr * ) {
1753 assertf( false, "AlternativeFinder should never see a resolved InitExpr." );
1754 }
1755
1756 void AlternativeFinder::Finder::postvisit( DeletedExpr * ) {
1757 assertf( false, "AlternativeFinder should never see a DeletedExpr." );
1758 }
[d807ca28]1759
1760 void AlternativeFinder::Finder::postvisit( GenericExpr * ) {
1761 assertf( false, "_Generic is not yet supported." );
1762 }
[51b73452]1763} // namespace ResolvExpr
[a32b204]1764
1765// Local Variables: //
1766// tab-width: 4 //
1767// mode: c++ //
1768// compile-command: "make install" //
1769// End: //
Note: See TracBrowser for help on using the repository browser.