source: translator/ResolvExpr/AlternativeFinder.cc @ 42dcae7

ADTaaron-thesisarm-ehast-experimentalcleanup-dtorsctordeferred_resndemanglerenumforall-pointer-decaygc_noraiijacob/cs343-translationjenkins-sandboxmemorynew-astnew-ast-unique-exprnew-envno_listpersistent-indexerpthread-emulationqualifiedEnumresolv-newstringwith_gc
Last change on this file since 42dcae7 was 51b7345, checked in by Peter A. Buhr <pabuhr@…>, 10 years ago

initial commit

  • Property mode set to 100644
File size: 37.3 KB
Line 
1/*
2 * This file is part of the Cforall project
3 *
4 * $Id: AlternativeFinder.cc,v 1.36 2005/08/29 20:14:15 rcbilson Exp $
5 *
6 */
7
8#include <list>
9#include <iterator>
10#include <algorithm>
11#include <functional>
12#include <cassert>
13
14#include "AlternativeFinder.h"
15#include "Alternative.h"
16#include "Cost.h"
17#include "typeops.h"
18#include "Unify.h"
19#include "RenameVars.h"
20#include "SynTree/Type.h"
21#include "SynTree/Declaration.h"
22#include "SynTree/Expression.h"
23#include "SynTree/Initializer.h"
24#include "SynTree/Visitor.h"
25#include "SymTab/Indexer.h"
26#include "SymTab/Mangler.h"
27#include "SynTree/TypeSubstitution.h"
28#include "SymTab/Validate.h"
29#include "Designators/Processor.h"
30#include "Tuples/TupleAssignment.h"
31#include "Tuples/NameMatcher.h"
32#include "utility.h"
33
34
35//#define DEBUG_COST
36
37namespace ResolvExpr {
38
39Expression *
40resolveInVoidContext( Expression *expr, const SymTab::Indexer &indexer, TypeEnvironment &env )
41{
42  CastExpr *castToVoid = new CastExpr( expr );
43
44  AlternativeFinder finder( indexer, env );
45  finder.findWithAdjustment( castToVoid );
46
47  // it's a property of the language that a cast expression has either 1 or 0 interpretations;
48  // if it has 0 interpretations, an exception has already been thrown.
49  assert( finder.get_alternatives().size() == 1 );
50  CastExpr *newExpr = dynamic_cast< CastExpr* >( finder.get_alternatives().front().expr );
51  assert( newExpr );
52  env = finder.get_alternatives().front().env;
53  return newExpr->get_arg()->clone();
54}
55
56namespace {
57
58  void
59  printAlts( const AltList &list, std::ostream &os, int indent = 0 )
60  {
61    for( AltList::const_iterator i = list.begin(); i != list.end(); ++i ) {
62      i->print( os, indent );
63      os << std::endl;
64    }
65  }
66
67  void
68  makeExprList( const AltList &in, std::list< Expression* > &out )
69  {
70    for( AltList::const_iterator i = in.begin(); i != in.end(); ++i ) {
71      out.push_back( i->expr->clone() );
72    }
73  }
74
75  Cost
76  sumCost( const AltList &in )
77  {
78    Cost total;
79    for( AltList::const_iterator i = in.begin(); i != in.end(); ++i ) {
80      total += i->cost;
81    }
82    return total;
83  }
84
85  struct PruneStruct
86  {
87    bool isAmbiguous;
88    AltList::iterator candidate;
89    PruneStruct() {}
90    PruneStruct( AltList::iterator candidate ): isAmbiguous( false ), candidate( candidate ) {}
91  };
92
93  template< typename InputIterator, typename OutputIterator >
94  void
95  pruneAlternatives( InputIterator begin, InputIterator end, OutputIterator out, const SymTab::Indexer &indexer )
96  {
97    // select the alternatives that have the minimum conversion cost for a particular set of result types
98    std::map< std::string, PruneStruct > selected;
99    for( AltList::iterator candidate = begin; candidate != end; ++candidate ) {
100      PruneStruct current( candidate );
101      std::string mangleName;
102      for( std::list< Type* >::const_iterator retType = candidate->expr->get_results().begin(); retType != candidate->expr->get_results().end(); ++retType ) {
103        Type *newType = (*retType)->clone();
104        candidate->env.apply( newType );
105        mangleName += SymTab::Mangler::mangle( newType );
106        delete newType;
107      }
108      std::map< std::string, PruneStruct >::iterator mapPlace = selected.find( mangleName );
109      if( mapPlace != selected.end() ) {
110        if( candidate->cost < mapPlace->second.candidate->cost ) {
111///           std::cout << "cost " << candidate->cost << " beats " << target->second.cost << std::endl;
112          selected[ mangleName ] = current;
113        } else if( candidate->cost == mapPlace->second.candidate->cost ) {
114///           std::cout << "marking ambiguous" << std::endl;
115          mapPlace->second.isAmbiguous = true;
116        }
117      } else {
118        selected[ mangleName ] = current;
119      }
120    }
121
122///     std::cout << "there are " << selected.size() << " alternatives before elimination" << std::endl;
123
124    // accept the alternatives that were unambiguous
125    for( std::map< std::string, PruneStruct >::iterator target = selected.begin(); target != selected.end(); ++target) {
126      if( !target->second.isAmbiguous ) {
127        Alternative &alt = *target->second.candidate;
128        for( std::list< Type* >::iterator result = alt.expr->get_results().begin(); result != alt.expr->get_results().end(); ++result ) {
129          alt.env.applyFree( *result );
130        }
131        *out++ = alt;
132      }
133    }
134
135  }
136
137  template< typename InputIterator, typename OutputIterator >
138  void
139  findMinCost( InputIterator begin, InputIterator end, OutputIterator out )
140  {
141    AltList alternatives;
142
143    // select the alternatives that have the minimum parameter cost
144    Cost minCost = Cost::infinity;
145    for( AltList::iterator i = begin; i != end; ++i ) {
146      if( i->cost < minCost ) {
147        minCost = i->cost;
148        i->cost = i->cvtCost;
149        alternatives.clear();
150        alternatives.push_back( *i );
151      } else if( i->cost == minCost ) {
152        i->cost = i->cvtCost;
153        alternatives.push_back( *i );
154      }
155    }
156    std::copy( alternatives.begin(), alternatives.end(), out );
157  }
158
159  template< typename InputIterator >
160  void
161  simpleCombineEnvironments( InputIterator begin, InputIterator end, TypeEnvironment &result )
162  {
163    while( begin != end ) {
164      result.simpleCombine( (*begin++).env );
165    }
166  }
167
168  void
169  renameTypes( Expression *expr )
170  {
171    for( std::list< Type* >::iterator i = expr->get_results().begin(); i != expr->get_results().end(); ++i ) {
172      (*i)->accept( global_renamer );
173    }
174  }
175}
176
177template< typename InputIterator, typename OutputIterator >
178void
179AlternativeFinder::findSubExprs( InputIterator begin, InputIterator end, OutputIterator out )
180{
181  while( begin != end ) {
182    AlternativeFinder finder( indexer, env );
183    finder.findWithAdjustment( *begin );
184    // XXX  either this
185    //Designators::fixDesignations( finder, (*begin++)->get_argName() );
186    // or XXX this
187    begin++;
188///     std::cout << "findSubExprs" << std::endl;
189///     printAlts( finder.alternatives, std::cout );
190    *out++ = finder;
191  }
192}
193
194AlternativeFinder::AlternativeFinder( const SymTab::Indexer &indexer, const TypeEnvironment &env )
195  : indexer( indexer ), env( env )
196{
197}
198
199void
200AlternativeFinder::find( Expression *expr, bool adjust )
201{
202  expr->accept( *this );
203  if( alternatives.empty() ) {
204    throw SemanticError( "No reasonable alternatives for expression ", expr );
205  }
206  for( AltList::iterator i = alternatives.begin(); i != alternatives.end(); ++i ) {
207    if( adjust ) {
208      adjustExprTypeList( i->expr->get_results().begin(), i->expr->get_results().end(), i->env, indexer );
209    }
210  }
211///   std::cout << "alternatives before prune:" << std::endl;
212///   printAlts( alternatives, std::cout );
213  AltList::iterator oldBegin = alternatives.begin();
214  pruneAlternatives( alternatives.begin(), alternatives.end(), front_inserter( alternatives ), indexer );
215  if( alternatives.begin() == oldBegin ) {
216    std::ostrstream stream;
217    stream << "Can't choose between alternatives for expression ";
218    expr->print( stream );
219    stream << "Alternatives are:";
220    AltList winners;
221    findMinCost( alternatives.begin(), alternatives.end(), back_inserter( winners ) );
222    printAlts( winners, stream, 8 );
223    throw SemanticError( std::string( stream.str(), stream.pcount() ) );
224  }
225  alternatives.erase( oldBegin, alternatives.end() );
226///   std::cout << "there are " << alternatives.size() << " alternatives after elimination" << std::endl;
227}
228
229void
230AlternativeFinder::findWithAdjustment( Expression *expr )
231{
232  find( expr, true );
233}
234
235template< typename StructOrUnionType >
236void
237AlternativeFinder::addAggMembers( StructOrUnionType *aggInst, Expression *expr, const Cost &newCost, const std::string &name )
238{
239  std::list< Declaration* > members;
240  aggInst->lookup( name, members );
241  for( std::list< Declaration* >::const_iterator i = members.begin(); i != members.end(); ++i ) {
242    if( DeclarationWithType *dwt = dynamic_cast< DeclarationWithType* >( *i ) ) {
243      alternatives.push_back( Alternative( new MemberExpr( dwt->clone(), expr->clone() ), env, newCost ) );
244      renameTypes( alternatives.back().expr );
245    } else {
246      assert( false );
247    }
248  }
249}
250
251void
252AlternativeFinder::visit(ApplicationExpr *applicationExpr)
253{
254  alternatives.push_back( Alternative( applicationExpr->clone(), env, Cost::zero ) );
255}
256
257Cost
258computeConversionCost( Alternative &alt, const SymTab::Indexer &indexer )
259{
260  ApplicationExpr *appExpr = dynamic_cast< ApplicationExpr* >( alt.expr );
261  assert( appExpr );
262  PointerType *pointer = dynamic_cast< PointerType* >( appExpr->get_function()->get_results().front() );
263  assert( pointer );
264  FunctionType *function = dynamic_cast< FunctionType* >( pointer->get_base() );
265  assert( function );
266
267  Cost convCost( 0, 0, 0 );
268  std::list< DeclarationWithType* >& formals = function->get_parameters();
269  std::list< DeclarationWithType* >::iterator formal = formals.begin();
270  std::list< Expression* >& actuals = appExpr->get_args();
271  for( std::list< Expression* >::iterator actualExpr = actuals.begin(); actualExpr != actuals.end(); ++actualExpr ) {
272///     std::cout << "actual expression:" << std::endl;
273///     (*actualExpr)->print( std::cout, 8 );
274///     std::cout << "--- results are" << std::endl;
275///     printAll( (*actualExpr)->get_results(), std::cout, 8 );
276    std::list< DeclarationWithType* >::iterator startFormal = formal;
277    Cost actualCost;
278    for( std::list< Type* >::iterator actual = (*actualExpr)->get_results().begin(); actual != (*actualExpr)->get_results().end(); ++actual ) {
279      if( formal == formals.end() ) {
280        if( function->get_isVarArgs() ) {
281          convCost += Cost( 1, 0, 0 );
282          break;
283        } else {
284          return Cost::infinity;
285        }
286      }
287///       std::cout << std::endl << "converting ";
288///       (*actual)->print( std::cout, 8 );
289///       std::cout << std::endl << " to ";
290///       (*formal)->get_type()->print( std::cout, 8 );
291      Cost newCost = conversionCost( *actual, (*formal)->get_type(), indexer, alt.env );
292///       std::cout << std::endl << "cost is" << newCost << std::endl;
293
294      if( newCost == Cost::infinity ) {
295        return newCost;
296      }
297      convCost += newCost;
298      actualCost += newCost;
299
300      convCost += Cost( 0, polyCost( (*formal)->get_type(), alt.env, indexer ) + polyCost( *actual, alt.env, indexer), 0 );
301
302      formal++;
303    }
304    if( actualCost != Cost( 0, 0, 0 ) ) {
305      std::list< DeclarationWithType* >::iterator startFormalPlusOne = startFormal;
306      startFormalPlusOne++;
307      if( formal == startFormalPlusOne ) {
308        // not a tuple type
309        Type *newType = (*startFormal)->get_type()->clone();
310        alt.env.apply( newType );
311        *actualExpr = new CastExpr( *actualExpr, newType );
312      } else {
313        TupleType *newType = new TupleType( Type::Qualifiers() );
314        for( std::list< DeclarationWithType* >::iterator i = startFormal; i != formal; ++i ) {
315          newType->get_types().push_back( (*i)->get_type()->clone() );
316        }
317        alt.env.apply( newType );
318        *actualExpr = new CastExpr( *actualExpr, newType );
319      }
320    }
321
322  }
323  if( formal != formals.end() ) {
324    return Cost::infinity;
325  }
326
327  for( InferredParams::const_iterator assert = appExpr->get_inferParams().begin(); assert != appExpr->get_inferParams().end(); ++assert ) {
328///     std::cout << std::endl << "converting ";
329///     assert->second.actualType->print( std::cout, 8 );
330///     std::cout << std::endl << " to ";
331///     assert->second.formalType->print( std::cout, 8 );
332    Cost newCost = conversionCost( assert->second.actualType, assert->second.formalType, indexer, alt.env );
333///     std::cout << std::endl << "cost of conversion is " << newCost << std::endl;
334    if( newCost == Cost::infinity ) {
335      return newCost;
336    }
337    convCost += newCost;
338
339    convCost += Cost( 0, polyCost( assert->second.formalType, alt.env, indexer ) + polyCost( assert->second.actualType, alt.env, indexer), 0 );
340  }
341
342  return convCost;
343}
344
345void
346makeUnifiableVars( Type *type, OpenVarSet &unifiableVars, AssertionSet &needAssertions )
347{
348  for( std::list< TypeDecl* >::const_iterator tyvar = type->get_forall().begin(); tyvar != type->get_forall().end(); ++tyvar ) {
349    unifiableVars[ (*tyvar)->get_name() ] = (*tyvar)->get_kind();
350    for( std::list< DeclarationWithType* >::iterator assert = (*tyvar)->get_assertions().begin(); assert != (*tyvar)->get_assertions().end(); ++assert ) {
351      needAssertions[ *assert ] = true;
352    }
353///     needAssertions.insert( needAssertions.end(), (*tyvar)->get_assertions().begin(), (*tyvar)->get_assertions().end() );
354  }
355}
356
357bool
358AlternativeFinder::instantiateFunction( std::list< DeclarationWithType* >& formals, /*const*/ AltList &actuals, bool isVarArgs, OpenVarSet& openVars, TypeEnvironment &resultEnv, AssertionSet &resultNeed, AssertionSet &resultHave )
359{
360  std::list< TypeEnvironment > toBeDone;
361  simpleCombineEnvironments( actuals.begin(), actuals.end(), resultEnv );
362  // make sure we don't widen any existing bindings
363  for( TypeEnvironment::iterator i = resultEnv.begin(); i != resultEnv.end(); ++i ) {
364    i->allowWidening  = false;
365  }
366  resultEnv.extractOpenVars( openVars );
367
368  /*
369  Tuples::NameMatcher matcher( formals );
370  try {
371    matcher.match( actuals );
372  } catch ( Tuples::NoMatch &e ) {
373    std::cerr << "Alternative doesn't match: " << e.message << std::endl;
374  }
375  */
376  std::list< DeclarationWithType* >::iterator formal = formals.begin();
377  for( AltList::const_iterator actualExpr = actuals.begin(); actualExpr != actuals.end(); ++actualExpr ) {
378    for( std::list< Type* >::iterator actual = actualExpr->expr->get_results().begin(); actual != actualExpr->expr->get_results().end(); ++actual ) {
379      if( formal == formals.end() ) {
380        return isVarArgs;
381      }
382///       std::cerr << "formal type is ";
383///       (*formal)->get_type()->print( std::cerr );
384///       std::cerr << std::endl << "actual type is ";
385///       (*actual)->print( std::cerr );
386///       std::cerr << std::endl;
387      if( !unify( (*formal)->get_type(), *actual, resultEnv, resultNeed, resultHave, openVars, indexer ) ) {
388        return false;
389      }
390      formal++;
391    }
392  }
393  // Handling of default values
394  while( formal != formals.end() ) {
395    if( ObjectDecl *od = dynamic_cast<ObjectDecl *>( *formal ) )
396      if( SingleInit *si = dynamic_cast<SingleInit *>( od->get_init() ))
397        // so far, only constant expressions are accepted as default values
398        if ( ConstantExpr *cnstexpr = dynamic_cast<ConstantExpr *>(si->get_value()) )
399          if ( Constant *cnst = dynamic_cast<Constant *>( cnstexpr->get_constant() ) )
400            if( unify( (*formal)->get_type(), cnst->get_type(), resultEnv, resultNeed, resultHave, openVars, indexer ) ) {
401              // XXX Don't know if this is right
402              actuals.push_back( Alternative( cnstexpr->clone(), env, Cost::zero ) );
403              formal++;
404              if (formal == formals.end()) break;
405            }
406    return false;
407  }
408  return true;
409}
410
411static const int recursionLimit = 10;
412
413void
414addToIndexer( AssertionSet &assertSet, SymTab::Indexer &indexer )
415{
416  for( AssertionSet::iterator i = assertSet.begin(); i != assertSet.end(); ++i ) {
417    if( i->second == true ) {
418      i->first->accept( indexer );
419    }
420  }
421}
422
423template< typename ForwardIterator, typename OutputIterator >
424void
425inferRecursive( ForwardIterator begin, ForwardIterator end, const Alternative &newAlt, OpenVarSet &openVars, const SymTab::Indexer &decls, const AssertionSet &newNeed, int level, const SymTab::Indexer &indexer, OutputIterator out )
426{
427  if( begin == end ) {
428    if( newNeed.empty() ) {
429      *out++ = newAlt;
430      return;
431    } else if( level >= recursionLimit ) {
432      throw SemanticError( "Too many recursive assertions" );
433    } else {
434      AssertionSet newerNeed;
435///       std::cerr << "recursing with new set:" << std::endl;
436///       printAssertionSet( newNeed, std::cerr, 8 );
437      inferRecursive( newNeed.begin(), newNeed.end(), newAlt, openVars, decls, newerNeed, level+1, indexer, out );
438      return;
439    }
440  }
441
442  ForwardIterator cur = begin++;
443  if( !cur->second ) {
444    inferRecursive( begin, end, newAlt, openVars, decls, newNeed, level, indexer, out );
445  }
446  DeclarationWithType *curDecl = cur->first;
447///   std::cerr << "inferRecursive: assertion is ";
448///   curDecl->print( std::cerr );
449///   std::cerr << std::endl;
450  std::list< DeclarationWithType* > candidates;
451  decls.lookupId( curDecl->get_name(), candidates );
452///   if( candidates.empty() ) { std::cout << "no candidates!" << std::endl; }
453  for( std::list< DeclarationWithType* >::const_iterator candidate = candidates.begin(); candidate != candidates.end(); ++candidate ) {
454///     std::cout << "inferRecursive: candidate is ";
455///     (*candidate)->print( std::cout );
456///     std::cout << std::endl;
457    AssertionSet newHave, newerNeed( newNeed );
458    TypeEnvironment newEnv( newAlt.env );
459    OpenVarSet newOpenVars( openVars );
460    Type *adjType = (*candidate)->get_type()->clone();
461    adjustExprType( adjType, newEnv, indexer );
462    adjType->accept( global_renamer );
463///     std::cerr << "unifying ";
464///     curDecl->get_type()->print( std::cerr );
465///     std::cerr << " with ";
466///     adjType->print( std::cerr );
467///     std::cerr << std::endl;
468    if( unify( curDecl->get_type(), adjType, newEnv, newerNeed, newHave, newOpenVars, indexer ) ) {
469///       std::cerr << "success!" << std::endl;
470      SymTab::Indexer newDecls( decls );
471      addToIndexer( newHave, newDecls );
472      Alternative newerAlt( newAlt );
473      newerAlt.env = newEnv;
474      assert( (*candidate)->get_uniqueId() );
475      Expression *varExpr = new VariableExpr( static_cast< DeclarationWithType* >( Declaration::declFromId( (*candidate)->get_uniqueId() ) ) );
476      deleteAll( varExpr->get_results() );
477      varExpr->get_results().clear();
478      varExpr->get_results().push_front( adjType->clone() );
479///       std::cout << "satisfying assertion " << curDecl->get_uniqueId() << " ";
480///       curDecl->print( std::cout );
481///       std::cout << " with declaration " << (*candidate)->get_uniqueId() << " ";
482///       (*candidate)->print( std::cout );
483///       std::cout << std::endl;
484      ApplicationExpr *appExpr = static_cast< ApplicationExpr* >( newerAlt.expr );
485      // XXX: this is a memory leak, but adjType can't be deleted because it might contain assertions
486      appExpr->get_inferParams()[ curDecl->get_uniqueId() ] = ParamEntry( (*candidate)->get_uniqueId(), adjType->clone(), curDecl->get_type()->clone(), varExpr );
487      inferRecursive( begin, end, newerAlt, newOpenVars, newDecls, newerNeed, level, indexer, out );
488    } else {
489      delete adjType;
490    }
491  }
492}
493
494template< typename OutputIterator >
495void
496AlternativeFinder::inferParameters( const AssertionSet &need, AssertionSet &have, const Alternative &newAlt, OpenVarSet &openVars, OutputIterator out )
497{
498///   std::cout << "inferParameters: assertions needed are" << std::endl;
499///   printAll( need, std::cout, 8 );
500  SymTab::Indexer decls( indexer );
501///   std::cout << "============= original indexer" << std::endl;
502///   indexer.print( std::cout );
503///   std::cout << "============= new indexer" << std::endl;
504///   decls.print( std::cout );
505  addToIndexer( have, decls );
506  AssertionSet newNeed;
507  inferRecursive( need.begin(), need.end(), newAlt, openVars, decls, newNeed, 0, indexer, out );
508///   std::cout << "declaration 14 is ";
509///   Declaration::declFromId
510///    *out++ = newAlt;
511}
512
513template< typename OutputIterator >
514void
515AlternativeFinder::makeFunctionAlternatives( const Alternative &func, FunctionType *funcType, AltList &actualAlt, OutputIterator out )
516{
517  OpenVarSet openVars;
518  AssertionSet resultNeed, resultHave;
519  TypeEnvironment resultEnv;
520  makeUnifiableVars( funcType, openVars, resultNeed );
521  if( instantiateFunction( funcType->get_parameters(), actualAlt, funcType->get_isVarArgs(), openVars, resultEnv, resultNeed, resultHave ) ) {
522    ApplicationExpr *appExpr = new ApplicationExpr( func.expr->clone() );
523    Alternative newAlt( appExpr, resultEnv, sumCost( actualAlt ) );
524    makeExprList( actualAlt, appExpr->get_args() );
525///     std::cout << "need assertions:" << std::endl;
526///     printAssertionSet( resultNeed, std::cout, 8 );
527    inferParameters( resultNeed, resultHave, newAlt, openVars, out );
528  }
529}
530
531void
532AlternativeFinder::visit(UntypedExpr *untypedExpr)
533{
534  bool doneInit = false;
535  AlternativeFinder funcOpFinder( indexer, env );
536
537  AlternativeFinder funcFinder( indexer, env );
538  {
539    NameExpr *fname;
540    if ( (fname = dynamic_cast<NameExpr *>(untypedExpr->get_function()))
541         && ( fname->get_name() == std::string("LabAddress")) ) {
542        alternatives.push_back( Alternative(untypedExpr, env, Cost()) );
543        return;
544      }
545  }
546
547  funcFinder.findWithAdjustment( untypedExpr->get_function() );
548  std::list< AlternativeFinder > argAlternatives;
549  findSubExprs( untypedExpr->begin_args(), untypedExpr->end_args(), back_inserter( argAlternatives ) );
550
551  std::list< AltList > possibilities;
552  combos( argAlternatives.begin(), argAlternatives.end(), back_inserter( possibilities ) );
553
554  Tuples::TupleAssignSpotter tassign(this);
555  if ( tassign.isTupleAssignment(untypedExpr, possibilities) ) {
556    // take care of possible tuple assignments, or discard expression
557    return;
558  } // else ...
559
560  AltList candidates;
561
562  for( AltList::const_iterator func = funcFinder.alternatives.begin(); func != funcFinder.alternatives.end(); ++func ) {
563///     std::cout << "working on alternative: " << std::endl;
564///     func->print( std::cout, 8 );
565    // check if the type is pointer to function
566    PointerType *pointer;
567    if( func->expr->get_results().size() == 1 && ( pointer = dynamic_cast< PointerType* >( func->expr->get_results().front() ) ) ) {
568      if( FunctionType *function = dynamic_cast< FunctionType* >( pointer->get_base() ) ) {
569        for( std::list< AltList >::iterator actualAlt = possibilities.begin(); actualAlt != possibilities.end(); ++actualAlt ) {
570          // XXX
571          //Designators::check_alternative( function, *actualAlt );
572          makeFunctionAlternatives( *func, function, *actualAlt, std::back_inserter( candidates ) );
573        }
574      } else if( TypeInstType *typeInst = dynamic_cast< TypeInstType* >( pointer->get_base() ) ) {
575        EqvClass eqvClass;
576        if( func->env.lookup( typeInst->get_name(), eqvClass ) && eqvClass.type ) {
577          if( FunctionType *function = dynamic_cast< FunctionType* >( eqvClass.type ) ) {
578            for( std::list< AltList >::iterator actualAlt = possibilities.begin(); actualAlt != possibilities.end(); ++actualAlt ) {
579              makeFunctionAlternatives( *func, function, *actualAlt, std::back_inserter( candidates ) );
580            }
581          }
582        }
583      }
584    } else {
585      // seek a function operator that's compatible
586      if( !doneInit ) {
587        doneInit = true;
588        NameExpr *opExpr = new NameExpr( "?()" );
589        try {
590          funcOpFinder.findWithAdjustment( opExpr );
591        } catch( SemanticError &e ) {
592          // it's ok if there aren't any defined function ops
593        }
594///         std::cout << "known function ops:" << std::endl;
595///         printAlts( funcOpFinder.alternatives, std::cout, 8 );
596      }
597
598      for( AltList::const_iterator funcOp = funcOpFinder.alternatives.begin(); funcOp != funcOpFinder.alternatives.end(); ++funcOp ) {
599        // check if the type is pointer to function
600        PointerType *pointer;
601        if( funcOp->expr->get_results().size() == 1
602                && ( pointer = dynamic_cast< PointerType* >( funcOp->expr->get_results().front() ) ) ) {
603          if ( FunctionType *function = dynamic_cast< FunctionType* >( pointer->get_base() ) ) {
604            for( std::list< AltList >::iterator actualAlt = possibilities.begin(); actualAlt != possibilities.end(); ++actualAlt ) {
605              AltList currentAlt;
606              currentAlt.push_back( *func );
607              currentAlt.insert( currentAlt.end(), actualAlt->begin(), actualAlt->end() );
608              makeFunctionAlternatives( *funcOp, function, currentAlt, std::back_inserter( candidates ) );
609            }
610          }
611        }
612      }
613    }
614  }
615
616  for( AltList::iterator withFunc = candidates.begin(); withFunc != candidates.end(); ++withFunc ) {
617    Cost cvtCost = computeConversionCost( *withFunc, indexer );
618
619#ifdef DEBUG_COST
620    ApplicationExpr *appExpr = dynamic_cast< ApplicationExpr* >( withFunc->expr );
621    assert( appExpr );
622    PointerType *pointer = dynamic_cast< PointerType* >( appExpr->get_function()->get_results().front() );
623    assert( pointer );
624    FunctionType *function = dynamic_cast< FunctionType* >( pointer->get_base() );
625    assert( function );
626    std::cout << "Case +++++++++++++" << std::endl;
627    std::cout << "formals are:" << std::endl;
628    printAll( function->get_parameters(), std::cout, 8 );
629    std::cout << "actuals are:" << std::endl;
630    printAll( appExpr->get_args(), std::cout, 8 );
631    std::cout << "bindings are:" << std::endl;
632    withFunc->env.print( std::cout, 8 );
633    std::cout << "cost of conversion is:" << cvtCost << std::endl;
634#endif
635
636    if( cvtCost != Cost::infinity ) {
637      withFunc->cvtCost = cvtCost;
638      alternatives.push_back( *withFunc );
639    }
640  }
641  candidates.clear();
642  candidates.splice( candidates.end(), alternatives );
643
644  findMinCost( candidates.begin(), candidates.end(), std::back_inserter( alternatives ) );
645}
646
647bool
648isLvalue( Expression *expr ) {
649  for( std::list< Type* >::const_iterator i = expr->get_results().begin(); i != expr->get_results().end(); ++i ) {
650    if( !(*i)->get_isLvalue() ) return false;
651  }
652  return true;
653}
654
655void
656AlternativeFinder::visit(AddressExpr *addressExpr)
657{
658  AlternativeFinder finder( indexer, env );
659  finder.find( addressExpr->get_arg() );
660  for( std::list< Alternative >::iterator i = finder.alternatives.begin(); i != finder.alternatives.end(); ++i ) {
661    if( isLvalue( i->expr ) ) {
662      alternatives.push_back( Alternative( new AddressExpr( i->expr->clone() ), i->env, i->cost ) );
663    }
664  }
665}
666
667void
668AlternativeFinder::visit(CastExpr *castExpr)
669{
670  for( std::list< Type* >::iterator i = castExpr->get_results().begin(); i != castExpr->get_results().end(); ++i ) {
671    SymTab::validateType( *i, &indexer );
672    adjustExprType( *i, env, indexer );
673  }
674
675  AlternativeFinder finder( indexer, env );
676  finder.findWithAdjustment( castExpr->get_arg() );
677
678  AltList candidates;
679  for( std::list< Alternative >::iterator i = finder.alternatives.begin(); i != finder.alternatives.end(); ++i ) {
680    AssertionSet needAssertions, haveAssertions;
681    OpenVarSet openVars;
682
683    // It's possible that a cast can throw away some values in a multiply-valued expression.
684    // (An example is a cast-to-void, which casts from one value to zero.)
685    // Figure out the prefix of the subexpression results that are cast directly.
686    // The candidate is invalid if it has fewer results than there are types to cast to.
687    int discardedValues = (*i).expr->get_results().size() - castExpr->get_results().size();
688    if( discardedValues < 0 ) continue;
689    std::list< Type* >::iterator candidate_end = (*i).expr->get_results().begin();
690    std::advance( candidate_end, castExpr->get_results().size() );
691    if( !unifyList( (*i).expr->get_results().begin(), candidate_end,
692        castExpr->get_results().begin(), castExpr->get_results().end(), i->env, needAssertions, haveAssertions, openVars, indexer ) ) continue;
693    Cost thisCost = castCostList( (*i).expr->get_results().begin(), candidate_end,
694        castExpr->get_results().begin(), castExpr->get_results().end(), indexer, i->env );
695    if( thisCost != Cost::infinity ) {
696      // count one safe conversion for each value that is thrown away
697      thisCost += Cost( 0, 0, discardedValues );
698      CastExpr *newExpr = castExpr->clone();
699      newExpr->set_arg( i->expr->clone() );
700      candidates.push_back( Alternative( newExpr, i->env, i->cost, thisCost ) );
701    }
702  }
703
704  // findMinCost selects the alternatives with the lowest "cost" members, but has the side effect
705  // of copying the cvtCost member to the cost member (since the old cost is now irrelevant).
706  // Thus, calling findMinCost twice selects first based on argument cost, then on conversion cost.
707  AltList minArgCost;
708  findMinCost( candidates.begin(), candidates.end(), std::back_inserter( minArgCost ) );
709  findMinCost( minArgCost.begin(), minArgCost.end(), std::back_inserter( alternatives ) );
710}
711
712void
713AlternativeFinder::visit(UntypedMemberExpr *memberExpr)
714{
715  AlternativeFinder funcFinder( indexer, env );
716  funcFinder.findWithAdjustment( memberExpr->get_aggregate() );
717
718  for( AltList::const_iterator agg = funcFinder.alternatives.begin(); agg != funcFinder.alternatives.end(); ++agg ) {
719    if( agg->expr->get_results().size() == 1 ) {
720      if( StructInstType *structInst = dynamic_cast< StructInstType* >( agg->expr->get_results().front() ) ) {
721        addAggMembers( structInst, agg->expr, agg->cost, memberExpr->get_member() );
722      } else if( UnionInstType *unionInst = dynamic_cast< UnionInstType* >( agg->expr->get_results().front() ) ) {
723        addAggMembers( unionInst, agg->expr, agg->cost, memberExpr->get_member() );
724      }
725    }
726  }
727}
728
729void
730AlternativeFinder::visit(MemberExpr *memberExpr)
731{
732  alternatives.push_back( Alternative( memberExpr->clone(), env, Cost::zero ) );
733}
734
735void
736AlternativeFinder::visit(NameExpr *nameExpr)
737{
738  std::list< DeclarationWithType* > declList;
739  indexer.lookupId( nameExpr->get_name(), declList );
740///     std::cerr << "nameExpr is " << nameExpr->get_name() << std::endl;
741  for( std::list< DeclarationWithType* >::iterator i = declList.begin(); i != declList.end(); ++i ) {
742    VariableExpr newExpr( *i, nameExpr->get_argName() );
743    alternatives.push_back( Alternative( newExpr.clone(), env, Cost() ) );
744///     std::cerr << "decl is ";
745///     (*i)->print( std::cerr );
746///     std::cerr << std::endl;
747///     std::cerr << "newExpr is ";
748///     newExpr.print( std::cerr );
749///     std::cerr << std::endl;
750    renameTypes( alternatives.back().expr );
751    if( StructInstType *structInst = dynamic_cast< StructInstType* >( (*i)->get_type() ) ) {
752      addAggMembers( structInst, &newExpr, Cost( 0, 0, 1 ), "" );
753    } else if( UnionInstType *unionInst = dynamic_cast< UnionInstType* >( (*i)->get_type() ) ) {
754      addAggMembers( unionInst, &newExpr, Cost( 0, 0, 1 ), "" );
755    }
756  }
757}
758
759void
760AlternativeFinder::visit(VariableExpr *variableExpr)
761{
762  alternatives.push_back( Alternative( variableExpr->clone(), env, Cost::zero ) );
763}
764
765void
766AlternativeFinder::visit(ConstantExpr *constantExpr)
767{
768  alternatives.push_back( Alternative( constantExpr->clone(), env, Cost::zero ) );
769}
770
771void
772AlternativeFinder::visit(SizeofExpr *sizeofExpr)
773{
774  if( sizeofExpr->get_isType() ) {
775    alternatives.push_back( Alternative( sizeofExpr->clone(), env, Cost::zero ) );
776  } else {
777    AlternativeFinder finder( indexer, env );
778    finder.find( sizeofExpr->get_expr() );
779    if( finder.alternatives.size() != 1 ) {
780      throw SemanticError( "Ambiguous expression in sizeof operand: ", sizeofExpr->get_expr() );
781    }
782    Alternative &choice = finder.alternatives.front();
783    alternatives.push_back( Alternative( new SizeofExpr( choice.expr->clone() ), choice.env, Cost::zero ) );
784  }
785}
786
787void
788AlternativeFinder::resolveAttr( DeclarationWithType *funcDecl, FunctionType *function, Type *argType, const TypeEnvironment &env )
789{
790  // assume no polymorphism
791  // assume no implicit conversions
792  assert( function->get_parameters().size() == 1 );
793///   std::cout << "resolvAttr: funcDecl is ";
794///   funcDecl->print( std::cout );
795///   std::cout << " argType is ";
796///   argType->print( std::cout );
797///   std::cout << std::endl;
798  if( typesCompatibleIgnoreQualifiers( argType, function->get_parameters().front()->get_type(), indexer, env ) ) {
799    alternatives.push_back( Alternative( new AttrExpr( new VariableExpr( funcDecl ), argType->clone() ), env, Cost::zero ) );
800    for( std::list< DeclarationWithType* >::iterator i = function->get_returnVals().begin(); i != function->get_returnVals().end(); ++i ) {
801      alternatives.back().expr->get_results().push_back( (*i)->get_type()->clone() );
802    }
803  }
804}
805
806void
807AlternativeFinder::visit(AttrExpr *attrExpr)
808{
809  // assume no 'pointer-to-attribute'
810  NameExpr *nameExpr = dynamic_cast< NameExpr* >( attrExpr->get_attr() );
811  assert( nameExpr );
812  std::list< DeclarationWithType* > attrList;
813  indexer.lookupId( nameExpr->get_name(), attrList );
814  if( attrExpr->get_isType() || attrExpr->get_expr() ) {
815    for( std::list< DeclarationWithType* >::iterator i = attrList.begin(); i != attrList.end(); ++i ) {
816      // check if the type is function
817      if( FunctionType *function = dynamic_cast< FunctionType* >( (*i)->get_type() ) ) {
818        // assume exactly one parameter
819        if( function->get_parameters().size() == 1 ) {
820          if( attrExpr->get_isType() ) {
821            resolveAttr( *i, function, attrExpr->get_type(), env );
822          } else {
823            AlternativeFinder finder( indexer, env );
824            finder.find( attrExpr->get_expr() );
825            for( AltList::iterator choice = finder.alternatives.begin(); choice != finder.alternatives.end(); ++choice ) {
826              if( choice->expr->get_results().size() == 1 ) {
827                resolveAttr(*i, function, choice->expr->get_results().front(), choice->env );
828              }
829            }
830          }
831        }
832      }
833    }
834  } else {
835    for( std::list< DeclarationWithType* >::iterator i = attrList.begin(); i != attrList.end(); ++i ) {
836      VariableExpr newExpr( *i );
837      alternatives.push_back( Alternative( newExpr.clone(), env, Cost() ) );
838      renameTypes( alternatives.back().expr );
839    }
840  }
841}
842
843void
844AlternativeFinder::visit(LogicalExpr *logicalExpr)
845{
846  AlternativeFinder firstFinder( indexer, env );
847  firstFinder.findWithAdjustment( logicalExpr->get_arg1() );
848  for( AltList::const_iterator first = firstFinder.alternatives.begin(); first != firstFinder.alternatives.end(); ++first ) {
849    AlternativeFinder secondFinder( indexer, first->env );
850    secondFinder.findWithAdjustment( logicalExpr->get_arg2() );
851    for( AltList::const_iterator second = secondFinder.alternatives.begin(); second != secondFinder.alternatives.end(); ++second ) {
852      LogicalExpr *newExpr = new LogicalExpr( first->expr->clone(), second->expr->clone(), logicalExpr->get_isAnd() );
853      alternatives.push_back( Alternative( newExpr, second->env, first->cost + second->cost ) );
854    }
855  }
856}
857
858void
859AlternativeFinder::visit(ConditionalExpr *conditionalExpr)
860{
861  AlternativeFinder firstFinder( indexer, env );
862  firstFinder.findWithAdjustment( conditionalExpr->get_arg1() );
863  for( AltList::const_iterator first = firstFinder.alternatives.begin(); first != firstFinder.alternatives.end(); ++first ) {
864    AlternativeFinder secondFinder( indexer, first->env );
865    secondFinder.findWithAdjustment( conditionalExpr->get_arg2() );
866    for( AltList::const_iterator second = secondFinder.alternatives.begin(); second != secondFinder.alternatives.end(); ++second ) {
867      AlternativeFinder thirdFinder( indexer, second->env );
868      thirdFinder.findWithAdjustment( conditionalExpr->get_arg3() );
869      for( AltList::const_iterator third = thirdFinder.alternatives.begin(); third != thirdFinder.alternatives.end(); ++third ) {
870        OpenVarSet openVars;
871        AssertionSet needAssertions, haveAssertions;
872        Alternative newAlt( 0, third->env, first->cost + second->cost + third->cost );
873        std::list< Type* > commonTypes;
874        if( unifyList( second->expr->get_results().begin(), second->expr->get_results().end(), third->expr->get_results().begin(), third->expr->get_results().end(), newAlt.env, needAssertions, haveAssertions, openVars, indexer, commonTypes ) ) {
875          ConditionalExpr *newExpr = new ConditionalExpr( first->expr->clone(), second->expr->clone(), third->expr->clone() );
876          std::list< Type* >::const_iterator original = second->expr->get_results().begin();
877          std::list< Type* >::const_iterator commonType = commonTypes.begin();
878          for( ; original != second->expr->get_results().end() && commonType != commonTypes.end(); ++original, ++commonType ) {
879            if( *commonType ) {
880              newExpr->get_results().push_back( *commonType );
881            } else {
882              newExpr->get_results().push_back( (*original)->clone() );
883            }
884          }
885          newAlt.expr = newExpr;
886          inferParameters( needAssertions, haveAssertions, newAlt, openVars, back_inserter( alternatives ) );
887        }
888      }
889    }
890  }
891}
892
893void
894AlternativeFinder::visit(CommaExpr *commaExpr)
895{
896  TypeEnvironment newEnv( env );
897  Expression *newFirstArg = resolveInVoidContext( commaExpr->get_arg1(), indexer, newEnv );
898  AlternativeFinder secondFinder( indexer, newEnv );
899  secondFinder.findWithAdjustment( commaExpr->get_arg2() );
900  for( AltList::const_iterator alt = secondFinder.alternatives.begin(); alt != secondFinder.alternatives.end(); ++alt ) {
901    alternatives.push_back( Alternative( new CommaExpr( newFirstArg->clone(), alt->expr->clone() ), alt->env, alt->cost ) );
902  }
903  delete newFirstArg;
904}
905
906void
907AlternativeFinder::visit(TupleExpr *tupleExpr)
908{
909  std::list< AlternativeFinder > subExprAlternatives;
910  findSubExprs( tupleExpr->get_exprs().begin(), tupleExpr->get_exprs().end(), back_inserter( subExprAlternatives ) );
911  std::list< AltList > possibilities;
912  combos( subExprAlternatives.begin(), subExprAlternatives.end(), back_inserter( possibilities ) );
913  for( std::list< AltList >::const_iterator i = possibilities.begin(); i != possibilities.end(); ++i ) {
914    TupleExpr *newExpr = new TupleExpr;
915    makeExprList( *i, newExpr->get_exprs() );
916    for( std::list< Expression* >::const_iterator resultExpr = newExpr->get_exprs().begin(); resultExpr != newExpr->get_exprs().end(); ++resultExpr ) {
917      for( std::list< Type* >::const_iterator resultType = (*resultExpr)->get_results().begin(); resultType != (*resultExpr)->get_results().end(); ++resultType ) {
918        newExpr->get_results().push_back( (*resultType)->clone() );
919      }
920    }
921
922    TypeEnvironment compositeEnv;
923    simpleCombineEnvironments( i->begin(), i->end(), compositeEnv );
924    alternatives.push_back( Alternative( newExpr, compositeEnv, sumCost( *i ) ) );
925  }
926}
927
928} // namespace ResolvExpr
Note: See TracBrowser for help on using the repository browser.