source: src/ResolvExpr/AlternativeFinder.cc@ c47ca77

ADT aaron-thesis arm-eh ast-experimental cleanup-dtors enum forall-pointer-decay jacob/cs343-translation jenkins-sandbox new-ast new-ast-unique-expr no_list persistent-indexer pthread-emulation qualifiedEnum
Last change on this file since c47ca77 was d97c3a4, checked in by Aaron Moss <a3moss@…>, 7 years ago

Fix new cost model by boosting precedence of safe costs

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