source: src/ResolvExpr/AlternativeFinder.cc@ 462a7c7

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

Port CandidateFinder::postvisit for UntypedExpr, stub dependencies

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