source: src/GenPoly/Box.cc@ bed4d37c

ADT aaron-thesis arm-eh ast-experimental cleanup-dtors ctor deferred_resn demangler enum forall-pointer-decay gc_noraii jacob/cs343-translation jenkins-sandbox memory new-ast new-ast-unique-expr new-env no_list persistent-indexer pthread-emulation qualifiedEnum resolv-new string stuck-waitfor-destruct with_gc
Last change on this file since bed4d37c was bed4d37c, checked in by Aaron Moss <a3moss@…>, 10 years ago

Improve member expression finding routine

  • Property mode set to 100644
File size: 66.9 KB
RevLine 
[51587aa]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//
[ae63a18]7// Box.cc --
[51587aa]8//
9// Author : Richard C. Bilson
10// Created On : Mon May 18 07:44:20 2015
[bd85400]11// Last Modified By : Peter A. Buhr
12// Last Modified On : Fri Feb 5 16:45:07 2016
13// Update Count : 286
[51587aa]14//
[51b73452]15
16#include <set>
[b1a6d6b]17#include <stack>
[51b73452]18#include <string>
19#include <iterator>
20#include <algorithm>
21#include <cassert>
22
23#include "Box.h"
[05d47278]24#include "InstantiateGeneric.h"
[51b73452]25#include "PolyMutator.h"
26#include "FindFunction.h"
[1194734]27#include "ScopedMap.h"
[51b73452]28#include "ScrubTyVars.h"
29
[68cd1ce]30#include "Parser/ParseNode.h"
31
[cdec5af]32#include "SynTree/Constant.h"
[51b73452]33#include "SynTree/Type.h"
34#include "SynTree/Expression.h"
35#include "SynTree/Initializer.h"
36#include "SynTree/Statement.h"
37#include "SynTree/Mutator.h"
[68cd1ce]38
[51b73452]39#include "ResolvExpr/TypeEnvironment.h"
[68cd1ce]40
[51b73452]41#include "SymTab/Mangler.h"
42
[d3b7937]43#include "Common/SemanticError.h"
44#include "Common/UniqueName.h"
45#include "Common/utility.h"
[51b73452]46
47#include <ext/functional> // temporary
48
49namespace GenPoly {
[01aeade]50 namespace {
51 const std::list<Label> noLabels;
52
[e56cfdb0]53 FunctionType *makeAdapterType( FunctionType *adaptee, const TyVarMap &tyVars );
54
[f8b961b]55 /// Replaces polymorphic return types with out-parameters, replaces calls to polymorphic functions with adapter calls as needed, and adds appropriate type variables to the function call
[01aeade]56 class Pass1 : public PolyMutator {
57 public:
58 Pass1();
59 virtual Expression *mutate( ApplicationExpr *appExpr );
60 virtual Expression *mutate( AddressExpr *addrExpr );
61 virtual Expression *mutate( UntypedExpr *expr );
62 virtual DeclarationWithType* mutate( FunctionDecl *functionDecl );
63 virtual TypeDecl *mutate( TypeDecl *typeDecl );
64 virtual Expression *mutate( CommaExpr *commaExpr );
65 virtual Expression *mutate( ConditionalExpr *condExpr );
[cf16f94]66 virtual Statement * mutate( ReturnStmt *returnStmt );
[01aeade]67 virtual Type *mutate( PointerType *pointerType );
[cf16f94]68 virtual Type * mutate( FunctionType *functionType );
[ae63a18]69
[01aeade]70 virtual void doBeginScope();
71 virtual void doEndScope();
72 private:
[05d47278]73 /// Makes a new temporary array holding the offsets of the fields of `type`, and returns a new variable expression referencing it
74 Expression *makeOffsetArray( StructInstType *type );
75 /// passes extra type parameters into a polymorphic function application
[01aeade]76 void passTypeVars( ApplicationExpr *appExpr, std::list< Expression *>::iterator &arg, const TyVarMap &exprTyVars );
[48ca586]77 /// wraps a function application with a new temporary for the out-parameter return value
[01aeade]78 Expression *addRetParam( ApplicationExpr *appExpr, FunctionType *function, Type *retType, std::list< Expression *>::iterator &arg );
[48ca586]79 /// Replaces all the type parameters of a generic type with their concrete equivalents under the current environment
80 void replaceParametersWithConcrete( ApplicationExpr *appExpr, std::list< Expression* >& params );
81 /// Replaces a polymorphic type with its concrete equivalant under the current environment (returns itself if concrete).
82 /// If `doClone` is set to false, will not clone interior types
83 Type *replaceWithConcrete( ApplicationExpr *appExpr, Type *type, bool doClone = true );
84 /// wraps a function application returning a polymorphic type with a new temporary for the out-parameter return value
85 Expression *addPolyRetParam( ApplicationExpr *appExpr, FunctionType *function, ReferenceToType *polyType, std::list< Expression *>::iterator &arg );
[01aeade]86 Expression *applyAdapter( ApplicationExpr *appExpr, FunctionType *function, std::list< Expression *>::iterator &arg, const TyVarMap &exprTyVars );
87 void boxParam( Type *formal, Expression *&arg, const TyVarMap &exprTyVars );
88 void boxParams( ApplicationExpr *appExpr, FunctionType *function, std::list< Expression *>::iterator &arg, const TyVarMap &exprTyVars );
89 void addInferredParams( ApplicationExpr *appExpr, FunctionType *functionType, std::list< Expression *>::iterator &arg, const TyVarMap &tyVars );
[1194734]90 /// Stores assignment operators from assertion list in local map of assignment operations
[01aeade]91 void findAssignOps( const std::list< TypeDecl *> &forall );
92 void passAdapters( ApplicationExpr *appExpr, FunctionType *functionType, const TyVarMap &exprTyVars );
93 FunctionDecl *makeAdapter( FunctionType *adaptee, FunctionType *realType, const std::string &mangleName, const TyVarMap &tyVars );
[05d47278]94 /// Replaces intrinsic operator functions with their arithmetic desugaring
[01aeade]95 Expression *handleIntrinsics( ApplicationExpr *appExpr );
[05d47278]96 /// Inserts a new temporary variable into the current scope with an auto-generated name
[01aeade]97 ObjectDecl *makeTemporary( Type *type );
[c29d9ce]98
[e56cfdb0]99 typedef std::map< std::string, DeclarationWithType *> AdapterMap;
[c29d9ce]100 std::map< std::string, DeclarationWithType *> assignOps;
[1194734]101 ScopedMap< std::string, DeclarationWithType *> scopedAssignOps;
[01aeade]102 std::stack< AdapterMap > adapters;
103 DeclarationWithType *retval;
104 bool useRetval;
105 UniqueName tempNamer;
106 };
107
[f8b961b]108 /// Moves polymorphic returns in function types to pointer-type parameters, adds type size and assertion parameters to parameter lists as well
[01aeade]109 class Pass2 : public PolyMutator {
110 public:
111 template< typename DeclClass >
112 DeclClass *handleDecl( DeclClass *decl, Type *type );
113 virtual DeclarationWithType *mutate( FunctionDecl *functionDecl );
114 virtual ObjectDecl *mutate( ObjectDecl *objectDecl );
115 virtual TypeDecl *mutate( TypeDecl *typeDecl );
116 virtual TypedefDecl *mutate( TypedefDecl *typedefDecl );
117 virtual Type *mutate( PointerType *pointerType );
118 virtual Type *mutate( FunctionType *funcType );
119 private:
120 void addAdapters( FunctionType *functionType );
[ae63a18]121
[01aeade]122 std::map< UniqueId, std::string > adapterName;
123 };
124
[2a4b088]125 /// Replaces member expressions for polymorphic types with calculated add-field-offset-and-dereference;
126 /// also fixes offsetof expressions.
[05d47278]127 class MemberExprFixer : public PolyMutator {
128 public:
129 template< typename DeclClass >
130 DeclClass *handleDecl( DeclClass *decl, Type *type );
131 virtual DeclarationWithType *mutate( FunctionDecl *functionDecl );
132 virtual ObjectDecl *mutate( ObjectDecl *objectDecl );
133 virtual TypedefDecl *mutate( TypedefDecl *objectDecl );
134 virtual TypeDecl *mutate( TypeDecl *objectDecl );
135 virtual Statement *mutate( DeclStmt *declStmt );
136 virtual Type *mutate( PointerType *pointerType );
137 virtual Type *mutate( FunctionType *funcType );
138 virtual Expression *mutate( MemberExpr *memberExpr );
[2a4b088]139 virtual Expression *mutate( OffsetofExpr *offsetofExpr );
[05d47278]140 };
[b4cd03b7]141
[f8b961b]142 /// Replaces initialization of polymorphic values with alloca, declaration of dtype/ftype with appropriate void expression, and sizeof expressions of polymorphic types with the proper variable
[01aeade]143 class Pass3 : public PolyMutator {
144 public:
145 template< typename DeclClass >
146 DeclClass *handleDecl( DeclClass *decl, Type *type );
147 virtual DeclarationWithType *mutate( FunctionDecl *functionDecl );
148 virtual ObjectDecl *mutate( ObjectDecl *objectDecl );
149 virtual TypedefDecl *mutate( TypedefDecl *objectDecl );
150 virtual TypeDecl *mutate( TypeDecl *objectDecl );
151 virtual Type *mutate( PointerType *pointerType );
152 virtual Type *mutate( FunctionType *funcType );
153 private:
154 };
155
156 } // anonymous namespace
157
158 void printAllNotBuiltin( const std::list< Declaration *>& translationUnit, std::ostream &os ) {
159 for ( std::list< Declaration *>::const_iterator i = translationUnit.begin(); i != translationUnit.end(); ++i ) {
160 if ( ! LinkageSpec::isBuiltin( (*i)->get_linkage() ) ) {
161 (*i)->print( os );
162 os << std::endl;
[6c3744e]163 } // if
[01aeade]164 } // for
[6c3744e]165 }
166
[05d47278]167 /// version of mutateAll with special handling for translation unit so you can check the end of the prelude when debugging
168 template< typename MutatorType >
169 inline void mutateTranslationUnit( std::list< Declaration* > &translationUnit, MutatorType &mutator ) {
170 bool seenIntrinsic = false;
171 SemanticError errors;
172 for ( typename std::list< Declaration* >::iterator i = translationUnit.begin(); i != translationUnit.end(); ++i ) {
173 try {
174 if ( *i ) {
175 if ( (*i)->get_linkage() == LinkageSpec::Intrinsic ) {
176 seenIntrinsic = true;
177 } else if ( seenIntrinsic ) {
178 seenIntrinsic = false; // break on this line when debugging for end of prelude
179 }
[b4cd03b7]180
[05d47278]181 *i = dynamic_cast< Declaration* >( (*i)->acceptMutator( mutator ) );
182 assert( *i );
183 } // if
184 } catch( SemanticError &e ) {
185 errors.append( e );
186 } // try
187 } // for
188 if ( ! errors.isEmpty() ) {
189 throw errors;
190 } // if
191 }
192
[01aeade]193 void box( std::list< Declaration *>& translationUnit ) {
194 Pass1 pass1;
195 Pass2 pass2;
[05d47278]196 MemberExprFixer memberFixer;
[01aeade]197 Pass3 pass3;
[05d47278]198 mutateTranslationUnit/*All*/( translationUnit, pass1 );
199 mutateTranslationUnit/*All*/( translationUnit, pass2 );
200 instantiateGeneric( translationUnit );
201 mutateTranslationUnit/*All*/( translationUnit, memberFixer );
202 mutateTranslationUnit/*All*/( translationUnit, pass3 );
[6c3744e]203 }
204
[01aeade]205 ////////////////////////////////////////// Pass1 ////////////////////////////////////////////////////
206
207 namespace {
[bdf1954]208 std::string makePolyMonoSuffix( FunctionType * function, const TyVarMap &tyVars ) {
209 std::stringstream name;
210
[ed1065c]211 // NOTE: this function previously used isPolyObj, which failed to produce
212 // the correct thing in some situations. It's not clear to me why this wasn't working.
213
[ae63a18]214 // if the return type or a parameter type involved polymorphic types, then the adapter will need
215 // to take those polymorphic types as pointers. Therefore, there can be two different functions
[bdf1954]216 // with the same mangled name, so we need to further mangle the names.
[ed1065c]217 for ( std::list< DeclarationWithType *>::iterator retval = function->get_returnVals().begin(); retval != function->get_returnVals().end(); ++retval ) {
[ffad73a]218 if ( isPolyType( (*retval)->get_type(), tyVars ) ) {
[ed1065c]219 name << "P";
220 } else {
221 name << "M";
222 }
[bdf1954]223 }
224 name << "_";
225 std::list< DeclarationWithType *> &paramList = function->get_parameters();
226 for ( std::list< DeclarationWithType *>::iterator arg = paramList.begin(); arg != paramList.end(); ++arg ) {
[ffad73a]227 if ( isPolyType( (*arg)->get_type(), tyVars ) ) {
[bdf1954]228 name << "P";
229 } else {
[ae63a18]230 name << "M";
[bdf1954]231 }
232 } // for
233 return name.str();
234 }
235
236 std::string mangleAdapterName( FunctionType * function, const TyVarMap &tyVars ) {
237 return SymTab::Mangler::mangle( function ) + makePolyMonoSuffix( function, tyVars );
238 }
239
[01aeade]240 std::string makeAdapterName( const std::string &mangleName ) {
241 return "_adapter" + mangleName;
242 }
[6c3744e]243
[56fcd77]244 Pass1::Pass1() : useRetval( false ), tempNamer( "_temp" ) {
[e56cfdb0]245 adapters.push(AdapterMap());
[01aeade]246 }
247
[1194734]248 /// returns T if the given declaration is: (*?=?)(T *, T) for some T (return not checked, but maybe should be), NULL otherwise
249 ReferenceToType *isAssignment( DeclarationWithType *decl ) {
[01aeade]250 if ( decl->get_name() == "?=?" ) {
[1194734]251 if ( FunctionType *funType = getFunctionType( decl->get_type() ) ) {
252 if ( funType->get_parameters().size() == 2 ) {
253 if ( PointerType *pointer = dynamic_cast< PointerType *>( funType->get_parameters().front()->get_type() ) ) {
254 if ( ReferenceToType *refType = dynamic_cast< ReferenceToType *>( pointer->get_base() ) ) {
255 if ( ReferenceToType *refType2 = dynamic_cast< ReferenceToType *>( funType->get_parameters().back()->get_type() ) ) {
256 if ( refType->get_name() == refType2->get_name() ) {
257 return refType;
[cf16f94]258 } // if
[01aeade]259 } // if
260 } // if
261 } // if
262 } // if
263 } // if
264 } // if
[1194734]265 return 0;
[01aeade]266 }
267
268 void Pass1::findAssignOps( const std::list< TypeDecl *> &forall ) {
[ed1065c]269 // what if a nested function uses an assignment operator?
270 // assignOps.clear();
[01aeade]271 for ( std::list< TypeDecl *>::const_iterator i = forall.begin(); i != forall.end(); ++i ) {
272 for ( std::list< DeclarationWithType *>::const_iterator assert = (*i)->get_assertions().begin(); assert != (*i)->get_assertions().end(); ++assert ) {
273 std::string typeName;
[1194734]274 if ( TypeInstType *typeInst = dynamic_cast< TypeInstType* >( isAssignment( *assert ) ) ) {
275 assignOps[ typeInst->get_name() ] = *assert;
[01aeade]276 } // if
277 } // for
278 } // for
279 }
280
[82dd287]281 DeclarationWithType *Pass1::mutate( FunctionDecl *functionDecl ) {
[1194734]282 // if this is a polymorphic assignment function, put it in the map for this scope
283 if ( ReferenceToType *refType = isAssignment( functionDecl ) ) {
284 if ( ! dynamic_cast< TypeInstType* >( refType ) ) {
285 scopedAssignOps.insert( refType->get_name(), functionDecl );
286 }
287 }
[b4cd03b7]288
[e56cfdb0]289 if ( functionDecl->get_statements() ) { // empty routine body ?
290 doBeginScope();
[01aeade]291 TyVarMap oldtyVars = scopeTyVars;
[ed1065c]292 std::map< std::string, DeclarationWithType *> oldassignOps = assignOps;
[01aeade]293 DeclarationWithType *oldRetval = retval;
294 bool oldUseRetval = useRetval;
[e56cfdb0]295
296 // process polymorphic return value
[01aeade]297 retval = 0;
[aadc9a4]298 if ( isPolyRet( functionDecl->get_functionType() ) && functionDecl->get_linkage() == LinkageSpec::Cforall ) {
[01aeade]299 retval = functionDecl->get_functionType()->get_returnVals().front();
[ae63a18]300
[01aeade]301 // give names to unnamed return values
302 if ( retval->get_name() == "" ) {
303 retval->set_name( "_retparm" );
304 retval->set_linkage( LinkageSpec::C );
305 } // if
306 } // if
[ae63a18]307
[e56cfdb0]308 FunctionType *functionType = functionDecl->get_functionType();
[01aeade]309 makeTyVarMap( functionDecl->get_functionType(), scopeTyVars );
310 findAssignOps( functionDecl->get_functionType()->get_forall() );
[e56cfdb0]311
312 std::list< DeclarationWithType *> &paramList = functionType->get_parameters();
313 std::list< FunctionType *> functions;
314 for ( std::list< TypeDecl *>::iterator tyVar = functionType->get_forall().begin(); tyVar != functionType->get_forall().end(); ++tyVar ) {
315 for ( std::list< DeclarationWithType *>::iterator assert = (*tyVar)->get_assertions().begin(); assert != (*tyVar)->get_assertions().end(); ++assert ) {
316 findFunction( (*assert)->get_type(), functions, scopeTyVars, needsAdapter );
317 } // for
318 } // for
319 for ( std::list< DeclarationWithType *>::iterator arg = paramList.begin(); arg != paramList.end(); ++arg ) {
320 findFunction( (*arg)->get_type(), functions, scopeTyVars, needsAdapter );
321 } // for
[b4cd03b7]322
[e56cfdb0]323 AdapterMap & adapters = Pass1::adapters.top();
324 for ( std::list< FunctionType *>::iterator funType = functions.begin(); funType != functions.end(); ++funType ) {
[bdf1954]325 std::string mangleName = mangleAdapterName( *funType, scopeTyVars );
[e56cfdb0]326 if ( adapters.find( mangleName ) == adapters.end() ) {
327 std::string adapterName = makeAdapterName( mangleName );
328 adapters.insert( std::pair< std::string, DeclarationWithType *>( mangleName, new ObjectDecl( adapterName, DeclarationNode::NoStorageClass, LinkageSpec::C, 0, new PointerType( Type::Qualifiers(), makeAdapterType( *funType, scopeTyVars ) ), 0 ) ) );
329 } // if
330 } // for
331
[01aeade]332 functionDecl->set_statements( functionDecl->get_statements()->acceptMutator( *this ) );
[ae63a18]333
[01aeade]334 scopeTyVars = oldtyVars;
[ed1065c]335 assignOps = oldassignOps;
[e56cfdb0]336 // std::cerr << "end FunctionDecl: ";
337 // for ( TyVarMap::iterator i = scopeTyVars.begin(); i != scopeTyVars.end(); ++i ) {
338 // std::cerr << i->first << " ";
339 // }
340 // std::cerr << "\n";
[01aeade]341 retval = oldRetval;
342 useRetval = oldUseRetval;
[e56cfdb0]343 doEndScope();
[01aeade]344 } // if
345 return functionDecl;
346 }
[6c3744e]347
[01aeade]348 TypeDecl *Pass1::mutate( TypeDecl *typeDecl ) {
349 scopeTyVars[ typeDecl->get_name() ] = typeDecl->get_kind();
350 return Mutator::mutate( typeDecl );
351 }
[6c3744e]352
[01aeade]353 Expression *Pass1::mutate( CommaExpr *commaExpr ) {
354 bool oldUseRetval = useRetval;
355 useRetval = false;
356 commaExpr->set_arg1( maybeMutate( commaExpr->get_arg1(), *this ) );
357 useRetval = oldUseRetval;
358 commaExpr->set_arg2( maybeMutate( commaExpr->get_arg2(), *this ) );
359 return commaExpr;
360 }
[6c3744e]361
[01aeade]362 Expression *Pass1::mutate( ConditionalExpr *condExpr ) {
363 bool oldUseRetval = useRetval;
364 useRetval = false;
365 condExpr->set_arg1( maybeMutate( condExpr->get_arg1(), *this ) );
366 useRetval = oldUseRetval;
367 condExpr->set_arg2( maybeMutate( condExpr->get_arg2(), *this ) );
368 condExpr->set_arg3( maybeMutate( condExpr->get_arg3(), *this ) );
369 return condExpr;
[6c3744e]370
[01aeade]371 }
[6c3744e]372
[05d47278]373 Expression *Pass1::makeOffsetArray( StructInstType *ty ) {
[4a79e3c9]374 std::list< Declaration* > &baseMembers = ty->get_baseStruct()->get_members();
[b4cd03b7]375
[05d47278]376 // make a new temporary array
377 Type *offsetType = new BasicType( Type::Qualifiers(), BasicType::LongUnsignedInt );
[4a79e3c9]378 std::stringstream lenGen;
379 lenGen << baseMembers.size();
380 ConstantExpr *lenExpr = new ConstantExpr( Constant( offsetType->clone(), lenGen.str() ) );
381 ObjectDecl *arrayTemp = makeTemporary( new ArrayType( Type::Qualifiers(), offsetType, lenExpr, false, false ) );
[05d47278]382
383 // build initializer list for temporary
384 std::list< Initializer* > inits;
[4a79e3c9]385 for ( std::list< Declaration* >::const_iterator member = baseMembers.begin(); member != baseMembers.end(); ++member ) {
[05d47278]386 DeclarationWithType *memberDecl;
387 if ( DeclarationWithType *origMember = dynamic_cast< DeclarationWithType* >( *member ) ) {
388 memberDecl = origMember->clone();
389 } else {
390 memberDecl = new ObjectDecl( (*member)->get_name(), DeclarationNode::NoStorageClass, LinkageSpec::Cforall, 0, offsetType->clone(), 0 );
391 }
392 inits.push_back( new SingleInit( new OffsetofExpr( ty->clone(), memberDecl ) ) );
393 }
394 arrayTemp->set_init( new ListInit( inits ) );
395
396 // return variable pointing to temporary
397 return new VariableExpr( arrayTemp );
398 }
[b4cd03b7]399
[01aeade]400 void Pass1::passTypeVars( ApplicationExpr *appExpr, std::list< Expression *>::iterator &arg, const TyVarMap &exprTyVars ) {
[7754cde]401 // pass size/align for type variables
[01aeade]402 for ( TyVarMap::const_iterator tyParm = exprTyVars.begin(); tyParm != exprTyVars.end(); ++tyParm ) {
403 ResolvExpr::EqvClass eqvClass;
404 assert( env );
405 if ( tyParm->second == TypeDecl::Any ) {
406 Type *concrete = env->lookup( tyParm->first );
407 if ( concrete ) {
408 arg = appExpr->get_args().insert( arg, new SizeofExpr( concrete->clone() ) );
409 arg++;
[db0b3ce]410 arg = appExpr->get_args().insert( arg, new AlignofExpr( concrete->clone() ) );
411 arg++;
[01aeade]412 } else {
413 throw SemanticError( "unbound type variable in application ", appExpr );
414 } // if
415 } // if
416 } // for
[7754cde]417
418 // add size/align for generic types to parameter list
419 if ( appExpr->get_function()->get_results().empty() ) return;
420 FunctionType *funcType = getFunctionType( appExpr->get_function()->get_results().front() );
421 assert( funcType );
[ae63a18]422
[7754cde]423 std::list< DeclarationWithType* >::const_iterator fnParm = funcType->get_parameters().begin();
424 std::list< Expression* >::const_iterator fnArg = arg;
[69911c11]425 std::set< std::string > seenTypes; //< names for generic types we've seen
[7754cde]426 for ( ; fnParm != funcType->get_parameters().end() && fnArg != appExpr->get_args().end(); ++fnParm, ++fnArg ) {
[32805db]427 Type *polyBase = hasPolyBase( (*fnParm)->get_type(), exprTyVars );
428 if ( polyBase && ! dynamic_cast< TypeInstType* >( polyBase ) ) {
429 std::string sizeName = sizeofName( polyBase );
[7754cde]430 if ( seenTypes.count( sizeName ) ) continue;
431
[32805db]432 VariableExpr *fnArgBase = getBaseVar( *fnArg );
433 assert( fnArgBase && ! fnArgBase->get_results().empty() );
434 Type *argBaseType = fnArgBase->get_results().front();
435 arg = appExpr->get_args().insert( arg, new SizeofExpr( argBaseType->clone() ) );
[7754cde]436 arg++;
[32805db]437 arg = appExpr->get_args().insert( arg, new AlignofExpr( argBaseType->clone() ) );
[7754cde]438 arg++;
[32805db]439 if ( dynamic_cast< StructInstType* >( polyBase ) ) {
440 if ( StructInstType *argBaseStructType = dynamic_cast< StructInstType* >( argBaseType ) ) {
441 arg = appExpr->get_args().insert( arg, makeOffsetArray( argBaseStructType ) );
[05d47278]442 arg++;
443 } else {
444 throw SemanticError( "Cannot pass non-struct type for generic struct" );
445 }
446 }
[7754cde]447
448 seenTypes.insert( sizeName );
449 }
450 }
[01aeade]451 }
[6c3744e]452
[01aeade]453 ObjectDecl *Pass1::makeTemporary( Type *type ) {
[68cd1ce]454 ObjectDecl *newObj = new ObjectDecl( tempNamer.newName(), DeclarationNode::NoStorageClass, LinkageSpec::C, 0, type, 0 );
[01aeade]455 stmtsToAdd.push_back( new DeclStmt( noLabels, newObj ) );
456 return newObj;
457 }
[6c3744e]458
[01aeade]459 Expression *Pass1::addRetParam( ApplicationExpr *appExpr, FunctionType *function, Type *retType, std::list< Expression *>::iterator &arg ) {
[cf16f94]460 // ***** Code Removal ***** After introducing a temporary variable for all return expressions, the following code appears superfluous.
461 // if ( useRetval ) {
462 // assert( retval );
463 // arg = appExpr->get_args().insert( arg, new VariableExpr( retval ) );
464 // arg++;
465 // } else {
466
467 // Create temporary to hold return value of polymorphic function and produce that temporary as a result
468 // using a comma expression. Possibly change comma expression into statement expression "{}" for multiple
469 // return values.
470 ObjectDecl *newObj = makeTemporary( retType->clone() );
471 Expression *paramExpr = new VariableExpr( newObj );
472 // If the type of the temporary is not polymorphic, box temporary by taking its address; otherwise the
473 // temporary is already boxed and can be used directly.
[5f6c42c]474 if ( ! isPolyType( newObj->get_type(), scopeTyVars, env ) ) {
[cf16f94]475 paramExpr = new AddressExpr( paramExpr );
[01aeade]476 } // if
[cf16f94]477 arg = appExpr->get_args().insert( arg, paramExpr ); // add argument to function call
478 arg++;
479 // Build a comma expression to call the function and emulate a normal return.
480 CommaExpr *commaExpr = new CommaExpr( appExpr, new VariableExpr( newObj ) );
481 commaExpr->set_env( appExpr->get_env() );
482 appExpr->set_env( 0 );
483 return commaExpr;
484 // } // if
485 // return appExpr;
[01aeade]486 }
[6c3744e]487
[48ca586]488 void Pass1::replaceParametersWithConcrete( ApplicationExpr *appExpr, std::list< Expression* >& params ) {
489 for ( std::list< Expression* >::iterator param = params.begin(); param != params.end(); ++param ) {
490 TypeExpr *paramType = dynamic_cast< TypeExpr* >( *param );
491 assert(paramType && "Aggregate parameters should be type expressions");
492 paramType->set_type( replaceWithConcrete( appExpr, paramType->get_type(), false ) );
493 }
494 }
[b4cd03b7]495
[48ca586]496 Type *Pass1::replaceWithConcrete( ApplicationExpr *appExpr, Type *type, bool doClone ) {
497 if ( TypeInstType *typeInst = dynamic_cast< TypeInstType * >( type ) ) {
498 Type *concrete = env->lookup( typeInst->get_name() );
499 if ( concrete == 0 ) {
500 throw SemanticError( "Unbound type variable " + typeInst->get_name() + " in ", appExpr );
501 } // if
502 return concrete;
503 } else if ( StructInstType *structType = dynamic_cast< StructInstType* >( type ) ) {
504 if ( doClone ) {
505 structType = structType->clone();
506 }
507 replaceParametersWithConcrete( appExpr, structType->get_parameters() );
508 return structType;
509 } else if ( UnionInstType *unionType = dynamic_cast< UnionInstType* >( type ) ) {
510 if ( doClone ) {
511 unionType = unionType->clone();
512 }
513 replaceParametersWithConcrete( appExpr, unionType->get_parameters() );
514 return unionType;
515 }
516 return type;
517 }
518
519 Expression *Pass1::addPolyRetParam( ApplicationExpr *appExpr, FunctionType *function, ReferenceToType *polyType, std::list< Expression *>::iterator &arg ) {
[01aeade]520 assert( env );
[48ca586]521 Type *concrete = replaceWithConcrete( appExpr, polyType );
[01aeade]522 return addRetParam( appExpr, function, concrete, arg );
523 }
[6c3744e]524
[01aeade]525 Expression *Pass1::applyAdapter( ApplicationExpr *appExpr, FunctionType *function, std::list< Expression *>::iterator &arg, const TyVarMap &tyVars ) {
526 Expression *ret = appExpr;
[ffad73a]527 if ( ! function->get_returnVals().empty() && isPolyType( function->get_returnVals().front()->get_type(), tyVars ) ) {
[01aeade]528 ret = addRetParam( appExpr, function, function->get_returnVals().front()->get_type(), arg );
529 } // if
[bdf1954]530 std::string mangleName = mangleAdapterName( function, tyVars );
[01aeade]531 std::string adapterName = makeAdapterName( mangleName );
[b1a6d6b]532
[b4cd03b7]533 // cast adaptee to void (*)(), since it may have any type inside a polymorphic function
534 Type * adapteeType = new PointerType( Type::Qualifiers(), new FunctionType( Type::Qualifiers(), true ) );
535 appExpr->get_args().push_front( new CastExpr( appExpr->get_function(), adapteeType ) );
[01aeade]536 appExpr->set_function( new NameExpr( adapterName ) );
[ae63a18]537
[01aeade]538 return ret;
539 }
[6c3744e]540
[01aeade]541 void Pass1::boxParam( Type *param, Expression *&arg, const TyVarMap &exprTyVars ) {
542 assert( ! arg->get_results().empty() );
[1cced28]543 if ( isPolyType( param, exprTyVars ) ) {
[01aeade]544 if ( dynamic_cast< TypeInstType *>( arg->get_results().front() ) ) {
545 // if the argument's type is a type parameter, we don't need to box again!
546 return;
547 } else if ( arg->get_results().front()->get_isLvalue() ) {
548 // VariableExpr and MemberExpr are lvalues
549 arg = new AddressExpr( arg );
550 } else {
[bd85400]551 // use type computed in unification to declare boxed variables
552 Type * newType = param->clone();
553 if ( env ) env->apply( newType );
554 ObjectDecl *newObj = new ObjectDecl( tempNamer.newName(), DeclarationNode::NoStorageClass, LinkageSpec::C, 0, newType, 0 );
[f6d7e0f]555 newObj->get_type()->get_qualifiers() = Type::Qualifiers(); // TODO: is this right???
[01aeade]556 stmtsToAdd.push_back( new DeclStmt( noLabels, newObj ) );
557 UntypedExpr *assign = new UntypedExpr( new NameExpr( "?=?" ) );
558 assign->get_args().push_back( new VariableExpr( newObj ) );
559 assign->get_args().push_back( arg );
560 stmtsToAdd.push_back( new ExprStmt( noLabels, assign ) );
561 arg = new AddressExpr( new VariableExpr( newObj ) );
562 } // if
563 } // if
564 }
[6c3744e]565
[b4cd03b7]566 /// cast parameters to polymorphic functions so that types are replaced with
567 /// void * if they are type parameters in the formal type.
568 /// this gets rid of warnings from gcc.
[01aeade]569 void addCast( Expression *&actual, Type *formal, const TyVarMap &tyVars ) {
[b4cd03b7]570 Type * newType = formal->clone();
571 if ( getFunctionType( newType ) ) {
572 newType = ScrubTyVars::scrub( newType, tyVars );
[01aeade]573 actual = new CastExpr( actual, newType );
574 } // if
575 }
[6c3744e]576
[01aeade]577 void Pass1::boxParams( ApplicationExpr *appExpr, FunctionType *function, std::list< Expression *>::iterator &arg, const TyVarMap &exprTyVars ) {
578 for ( std::list< DeclarationWithType *>::const_iterator param = function->get_parameters().begin(); param != function->get_parameters().end(); ++param, ++arg ) {
579 assert( arg != appExpr->get_args().end() );
580 addCast( *arg, (*param)->get_type(), exprTyVars );
581 boxParam( (*param)->get_type(), *arg, exprTyVars );
582 } // for
583 }
[6c3744e]584
[01aeade]585 void Pass1::addInferredParams( ApplicationExpr *appExpr, FunctionType *functionType, std::list< Expression *>::iterator &arg, const TyVarMap &tyVars ) {
586 std::list< Expression *>::iterator cur = arg;
587 for ( std::list< TypeDecl *>::iterator tyVar = functionType->get_forall().begin(); tyVar != functionType->get_forall().end(); ++tyVar ) {
588 for ( std::list< DeclarationWithType *>::iterator assert = (*tyVar)->get_assertions().begin(); assert != (*tyVar)->get_assertions().end(); ++assert ) {
589 InferredParams::const_iterator inferParam = appExpr->get_inferParams().find( (*assert)->get_uniqueId() );
[698664b3]590 assert( inferParam != appExpr->get_inferParams().end() && "NOTE: Explicit casts of polymorphic functions to compatible monomorphic functions are currently unsupported" );
[01aeade]591 Expression *newExpr = inferParam->second.expr->clone();
592 addCast( newExpr, (*assert)->get_type(), tyVars );
593 boxParam( (*assert)->get_type(), newExpr, tyVars );
594 appExpr->get_args().insert( cur, newExpr );
595 } // for
596 } // for
597 }
[6c3744e]598
[01aeade]599 void makeRetParm( FunctionType *funcType ) {
600 DeclarationWithType *retParm = funcType->get_returnVals().front();
[6c3744e]601
[01aeade]602 // make a new parameter that is a pointer to the type of the old return value
603 retParm->set_type( new PointerType( Type::Qualifiers(), retParm->get_type() ) );
604 funcType->get_parameters().push_front( retParm );
[6c3744e]605
[01aeade]606 // we don't need the return value any more
607 funcType->get_returnVals().clear();
608 }
[6c3744e]609
[01aeade]610 FunctionType *makeAdapterType( FunctionType *adaptee, const TyVarMap &tyVars ) {
611 // actually make the adapter type
612 FunctionType *adapter = adaptee->clone();
[ffad73a]613 if ( ! adapter->get_returnVals().empty() && isPolyType( adapter->get_returnVals().front()->get_type(), tyVars ) ) {
[01aeade]614 makeRetParm( adapter );
615 } // if
[68cd1ce]616 adapter->get_parameters().push_front( new ObjectDecl( "", DeclarationNode::NoStorageClass, LinkageSpec::C, 0, new PointerType( Type::Qualifiers(), new FunctionType( Type::Qualifiers(), true ) ), 0 ) );
[01aeade]617 return adapter;
618 }
[6c3744e]619
[01aeade]620 Expression *makeAdapterArg( DeclarationWithType *param, DeclarationWithType *arg, DeclarationWithType *realParam, const TyVarMap &tyVars ) {
621 assert( param );
622 assert( arg );
[ffad73a]623 if ( isPolyType( realParam->get_type(), tyVars ) ) {
[e56cfdb0]624 if ( dynamic_cast<TypeInstType *>(arg->get_type()) == NULL ) {
625 UntypedExpr *deref = new UntypedExpr( new NameExpr( "*?" ) );
626 deref->get_args().push_back( new CastExpr( new VariableExpr( param ), new PointerType( Type::Qualifiers(), arg->get_type()->clone() ) ) );
627 deref->get_results().push_back( arg->get_type()->clone() );
628 return deref;
629 } // if
[01aeade]630 } // if
631 return new VariableExpr( param );
632 }
[6c3744e]633
[01aeade]634 void addAdapterParams( ApplicationExpr *adapteeApp, std::list< DeclarationWithType *>::iterator arg, std::list< DeclarationWithType *>::iterator param, std::list< DeclarationWithType *>::iterator paramEnd, std::list< DeclarationWithType *>::iterator realParam, const TyVarMap &tyVars ) {
635 UniqueName paramNamer( "_p" );
636 for ( ; param != paramEnd; ++param, ++arg, ++realParam ) {
637 if ( (*param)->get_name() == "" ) {
638 (*param)->set_name( paramNamer.newName() );
639 (*param)->set_linkage( LinkageSpec::C );
640 } // if
641 adapteeApp->get_args().push_back( makeAdapterArg( *param, *arg, *realParam, tyVars ) );
642 } // for
643 }
[6c3744e]644
[b1a6d6b]645
646
[01aeade]647 FunctionDecl *Pass1::makeAdapter( FunctionType *adaptee, FunctionType *realType, const std::string &mangleName, const TyVarMap &tyVars ) {
648 FunctionType *adapterType = makeAdapterType( adaptee, tyVars );
649 adapterType = ScrubTyVars::scrub( adapterType, tyVars );
650 DeclarationWithType *adapteeDecl = adapterType->get_parameters().front();
651 adapteeDecl->set_name( "_adaptee" );
652 ApplicationExpr *adapteeApp = new ApplicationExpr( new CastExpr( new VariableExpr( adapteeDecl ), new PointerType( Type::Qualifiers(), realType ) ) );
653 Statement *bodyStmt;
[ae63a18]654
[01aeade]655 std::list< TypeDecl *>::iterator tyArg = realType->get_forall().begin();
656 std::list< TypeDecl *>::iterator tyParam = adapterType->get_forall().begin();
657 std::list< TypeDecl *>::iterator realTyParam = adaptee->get_forall().begin();
658 for ( ; tyParam != adapterType->get_forall().end(); ++tyArg, ++tyParam, ++realTyParam ) {
659 assert( tyArg != realType->get_forall().end() );
660 std::list< DeclarationWithType *>::iterator assertArg = (*tyArg)->get_assertions().begin();
661 std::list< DeclarationWithType *>::iterator assertParam = (*tyParam)->get_assertions().begin();
662 std::list< DeclarationWithType *>::iterator realAssertParam = (*realTyParam)->get_assertions().begin();
663 for ( ; assertParam != (*tyParam)->get_assertions().end(); ++assertArg, ++assertParam, ++realAssertParam ) {
664 assert( assertArg != (*tyArg)->get_assertions().end() );
665 adapteeApp->get_args().push_back( makeAdapterArg( *assertParam, *assertArg, *realAssertParam, tyVars ) );
666 } // for
667 } // for
[ae63a18]668
[01aeade]669 std::list< DeclarationWithType *>::iterator arg = realType->get_parameters().begin();
670 std::list< DeclarationWithType *>::iterator param = adapterType->get_parameters().begin();
671 std::list< DeclarationWithType *>::iterator realParam = adaptee->get_parameters().begin();
672 param++; // skip adaptee parameter
673 if ( realType->get_returnVals().empty() ) {
674 addAdapterParams( adapteeApp, arg, param, adapterType->get_parameters().end(), realParam, tyVars );
675 bodyStmt = new ExprStmt( noLabels, adapteeApp );
[ffad73a]676 } else if ( isPolyType( adaptee->get_returnVals().front()->get_type(), tyVars ) ) {
[01aeade]677 if ( (*param)->get_name() == "" ) {
678 (*param)->set_name( "_ret" );
679 (*param)->set_linkage( LinkageSpec::C );
680 } // if
681 UntypedExpr *assign = new UntypedExpr( new NameExpr( "?=?" ) );
682 UntypedExpr *deref = new UntypedExpr( new NameExpr( "*?" ) );
683 deref->get_args().push_back( new CastExpr( new VariableExpr( *param++ ), new PointerType( Type::Qualifiers(), realType->get_returnVals().front()->get_type()->clone() ) ) );
684 assign->get_args().push_back( deref );
685 addAdapterParams( adapteeApp, arg, param, adapterType->get_parameters().end(), realParam, tyVars );
686 assign->get_args().push_back( adapteeApp );
687 bodyStmt = new ExprStmt( noLabels, assign );
688 } else {
689 // adapter for a function that returns a monomorphic value
690 addAdapterParams( adapteeApp, arg, param, adapterType->get_parameters().end(), realParam, tyVars );
691 bodyStmt = new ReturnStmt( noLabels, adapteeApp );
692 } // if
693 CompoundStmt *adapterBody = new CompoundStmt( noLabels );
694 adapterBody->get_kids().push_back( bodyStmt );
695 std::string adapterName = makeAdapterName( mangleName );
[de62360d]696 return new FunctionDecl( adapterName, DeclarationNode::NoStorageClass, LinkageSpec::C, adapterType, adapterBody, false, false );
[01aeade]697 }
[6c3744e]698
[c29d9ce]699 void Pass1::passAdapters( ApplicationExpr * appExpr, FunctionType * functionType, const TyVarMap & exprTyVars ) {
[e497c1d]700 // collect a list of function types passed as parameters or implicit parameters (assertions)
[01aeade]701 std::list< DeclarationWithType *> &paramList = functionType->get_parameters();
702 std::list< FunctionType *> functions;
703 for ( std::list< TypeDecl *>::iterator tyVar = functionType->get_forall().begin(); tyVar != functionType->get_forall().end(); ++tyVar ) {
704 for ( std::list< DeclarationWithType *>::iterator assert = (*tyVar)->get_assertions().begin(); assert != (*tyVar)->get_assertions().end(); ++assert ) {
705 findFunction( (*assert)->get_type(), functions, exprTyVars, needsAdapter );
706 } // for
707 } // for
708 for ( std::list< DeclarationWithType *>::iterator arg = paramList.begin(); arg != paramList.end(); ++arg ) {
709 findFunction( (*arg)->get_type(), functions, exprTyVars, needsAdapter );
710 } // for
[e497c1d]711
[e56cfdb0]712 // parameter function types for which an appropriate adapter has been generated. we cannot use the types
713 // after applying substitutions, since two different parameter types may be unified to the same type
[01aeade]714 std::set< std::string > adaptersDone;
[e497c1d]715
[01aeade]716 for ( std::list< FunctionType *>::iterator funType = functions.begin(); funType != functions.end(); ++funType ) {
[c29d9ce]717 FunctionType *originalFunction = (*funType)->clone();
[01aeade]718 FunctionType *realFunction = (*funType)->clone();
719 std::string mangleName = SymTab::Mangler::mangle( realFunction );
[e497c1d]720
[e56cfdb0]721 // only attempt to create an adapter or pass one as a parameter if we haven't already done so for this
722 // pre-substitution parameter function type.
[01aeade]723 if ( adaptersDone.find( mangleName ) == adaptersDone.end() ) {
[e497c1d]724 adaptersDone.insert( adaptersDone.begin(), mangleName );
[ae63a18]725
[e56cfdb0]726 // apply substitution to type variables to figure out what the adapter's type should look like
[e497c1d]727 assert( env );
728 env->apply( realFunction );
[ae63a18]729 mangleName = SymTab::Mangler::mangle( realFunction );
[bdf1954]730 mangleName += makePolyMonoSuffix( originalFunction, exprTyVars );
[e497c1d]731
[e56cfdb0]732 AdapterMap & adapters = Pass1::adapters.top();
733 AdapterMap::iterator adapter = adapters.find( mangleName );
734 if ( adapter == adapters.end() ) {
735 // adapter has not been created yet in the current scope, so define it
736 FunctionDecl *newAdapter = makeAdapter( *funType, realFunction, mangleName, exprTyVars );
737 adapter = adapters.insert( adapters.begin(), std::pair< std::string, DeclarationWithType *>( mangleName, newAdapter ) );
738 stmtsToAdd.push_back( new DeclStmt( noLabels, newAdapter ) );
[c29d9ce]739 } // if
[e56cfdb0]740 assert( adapter != adapters.end() );
741
742 // add the appropriate adapter as a parameter
743 appExpr->get_args().push_front( new VariableExpr( adapter->second ) );
[01aeade]744 } // if
745 } // for
[e56cfdb0]746 } // passAdapters
[6c3744e]747
[78dd0da]748 Expression *makeIncrDecrExpr( ApplicationExpr *appExpr, Type *polyType, bool isIncr ) {
[01aeade]749 NameExpr *opExpr;
750 if ( isIncr ) {
751 opExpr = new NameExpr( "?+=?" );
752 } else {
753 opExpr = new NameExpr( "?-=?" );
[6c3744e]754 } // if
[01aeade]755 UntypedExpr *addAssign = new UntypedExpr( opExpr );
756 if ( AddressExpr *address = dynamic_cast< AddressExpr *>( appExpr->get_args().front() ) ) {
757 addAssign->get_args().push_back( address->get_arg() );
758 } else {
759 addAssign->get_args().push_back( appExpr->get_args().front() );
[6c3744e]760 } // if
[78dd0da]761 addAssign->get_args().push_back( new NameExpr( sizeofName( polyType ) ) );
[01aeade]762 addAssign->get_results().front() = appExpr->get_results().front()->clone();
763 if ( appExpr->get_env() ) {
764 addAssign->set_env( appExpr->get_env() );
[6c3744e]765 appExpr->set_env( 0 );
766 } // if
[01aeade]767 appExpr->get_args().clear();
768 delete appExpr;
769 return addAssign;
770 }
771
772 Expression *Pass1::handleIntrinsics( ApplicationExpr *appExpr ) {
773 if ( VariableExpr *varExpr = dynamic_cast< VariableExpr *>( appExpr->get_function() ) ) {
774 if ( varExpr->get_var()->get_linkage() == LinkageSpec::Intrinsic ) {
775 if ( varExpr->get_var()->get_name() == "?[?]" ) {
776 assert( ! appExpr->get_results().empty() );
777 assert( appExpr->get_args().size() == 2 );
[ffad73a]778 Type *baseType1 = isPolyPtr( appExpr->get_args().front()->get_results().front(), scopeTyVars, env );
779 Type *baseType2 = isPolyPtr( appExpr->get_args().back()->get_results().front(), scopeTyVars, env );
[ae63a18]780 assert( ! baseType1 || ! baseType2 ); // the arguments cannot both be polymorphic pointers
[01aeade]781 UntypedExpr *ret = 0;
[ae63a18]782 if ( baseType1 || baseType2 ) { // one of the arguments is a polymorphic pointer
[01aeade]783 ret = new UntypedExpr( new NameExpr( "?+?" ) );
784 } // if
[ffad73a]785 if ( baseType1 ) {
[01aeade]786 UntypedExpr *multiply = new UntypedExpr( new NameExpr( "?*?" ) );
787 multiply->get_args().push_back( appExpr->get_args().back() );
[ffad73a]788 multiply->get_args().push_back( new NameExpr( sizeofName( baseType1 ) ) );
[01aeade]789 ret->get_args().push_back( appExpr->get_args().front() );
790 ret->get_args().push_back( multiply );
[ffad73a]791 } else if ( baseType2 ) {
[01aeade]792 UntypedExpr *multiply = new UntypedExpr( new NameExpr( "?*?" ) );
793 multiply->get_args().push_back( appExpr->get_args().front() );
[ffad73a]794 multiply->get_args().push_back( new NameExpr( sizeofName( baseType2 ) ) );
[01aeade]795 ret->get_args().push_back( multiply );
796 ret->get_args().push_back( appExpr->get_args().back() );
797 } // if
[ffad73a]798 if ( baseType1 || baseType2 ) {
[01aeade]799 ret->get_results().push_front( appExpr->get_results().front()->clone() );
800 if ( appExpr->get_env() ) {
801 ret->set_env( appExpr->get_env() );
802 appExpr->set_env( 0 );
803 } // if
804 appExpr->get_args().clear();
805 delete appExpr;
806 return ret;
807 } // if
808 } else if ( varExpr->get_var()->get_name() == "*?" ) {
809 assert( ! appExpr->get_results().empty() );
810 assert( ! appExpr->get_args().empty() );
[ffad73a]811 if ( isPolyType( appExpr->get_results().front(), scopeTyVars, env ) ) {
[01aeade]812 Expression *ret = appExpr->get_args().front();
813 delete ret->get_results().front();
814 ret->get_results().front() = appExpr->get_results().front()->clone();
815 if ( appExpr->get_env() ) {
816 ret->set_env( appExpr->get_env() );
817 appExpr->set_env( 0 );
818 } // if
819 appExpr->get_args().clear();
820 delete appExpr;
821 return ret;
822 } // if
823 } else if ( varExpr->get_var()->get_name() == "?++" || varExpr->get_var()->get_name() == "?--" ) {
824 assert( ! appExpr->get_results().empty() );
825 assert( appExpr->get_args().size() == 1 );
[ffad73a]826 if ( Type *baseType = isPolyPtr( appExpr->get_results().front(), scopeTyVars, env ) ) {
[01aeade]827 Type *tempType = appExpr->get_results().front()->clone();
828 if ( env ) {
829 env->apply( tempType );
830 } // if
831 ObjectDecl *newObj = makeTemporary( tempType );
832 VariableExpr *tempExpr = new VariableExpr( newObj );
833 UntypedExpr *assignExpr = new UntypedExpr( new NameExpr( "?=?" ) );
834 assignExpr->get_args().push_back( tempExpr->clone() );
835 if ( AddressExpr *address = dynamic_cast< AddressExpr *>( appExpr->get_args().front() ) ) {
836 assignExpr->get_args().push_back( address->get_arg()->clone() );
837 } else {
838 assignExpr->get_args().push_back( appExpr->get_args().front()->clone() );
839 } // if
[ffad73a]840 CommaExpr *firstComma = new CommaExpr( assignExpr, makeIncrDecrExpr( appExpr, baseType, varExpr->get_var()->get_name() == "?++" ) );
[01aeade]841 return new CommaExpr( firstComma, tempExpr );
842 } // if
843 } else if ( varExpr->get_var()->get_name() == "++?" || varExpr->get_var()->get_name() == "--?" ) {
844 assert( ! appExpr->get_results().empty() );
845 assert( appExpr->get_args().size() == 1 );
[ffad73a]846 if ( Type *baseType = isPolyPtr( appExpr->get_results().front(), scopeTyVars, env ) ) {
847 return makeIncrDecrExpr( appExpr, baseType, varExpr->get_var()->get_name() == "++?" );
[01aeade]848 } // if
849 } else if ( varExpr->get_var()->get_name() == "?+?" || varExpr->get_var()->get_name() == "?-?" ) {
850 assert( ! appExpr->get_results().empty() );
851 assert( appExpr->get_args().size() == 2 );
[ffad73a]852 Type *baseType1 = isPolyPtr( appExpr->get_args().front()->get_results().front(), scopeTyVars, env );
853 Type *baseType2 = isPolyPtr( appExpr->get_args().back()->get_results().front(), scopeTyVars, env );
854 if ( baseType1 && baseType2 ) {
[01aeade]855 UntypedExpr *divide = new UntypedExpr( new NameExpr( "?/?" ) );
856 divide->get_args().push_back( appExpr );
[ffad73a]857 divide->get_args().push_back( new NameExpr( sizeofName( baseType1 ) ) );
[01aeade]858 divide->get_results().push_front( appExpr->get_results().front()->clone() );
859 if ( appExpr->get_env() ) {
860 divide->set_env( appExpr->get_env() );
861 appExpr->set_env( 0 );
862 } // if
863 return divide;
[ffad73a]864 } else if ( baseType1 ) {
[01aeade]865 UntypedExpr *multiply = new UntypedExpr( new NameExpr( "?*?" ) );
866 multiply->get_args().push_back( appExpr->get_args().back() );
[ffad73a]867 multiply->get_args().push_back( new NameExpr( sizeofName( baseType1 ) ) );
[01aeade]868 appExpr->get_args().back() = multiply;
[ffad73a]869 } else if ( baseType2 ) {
[01aeade]870 UntypedExpr *multiply = new UntypedExpr( new NameExpr( "?*?" ) );
871 multiply->get_args().push_back( appExpr->get_args().front() );
[ffad73a]872 multiply->get_args().push_back( new NameExpr( sizeofName( baseType2 ) ) );
[01aeade]873 appExpr->get_args().front() = multiply;
874 } // if
875 } else if ( varExpr->get_var()->get_name() == "?+=?" || varExpr->get_var()->get_name() == "?-=?" ) {
876 assert( ! appExpr->get_results().empty() );
877 assert( appExpr->get_args().size() == 2 );
[ffad73a]878 Type *baseType = isPolyPtr( appExpr->get_results().front(), scopeTyVars, env );
879 if ( baseType ) {
[01aeade]880 UntypedExpr *multiply = new UntypedExpr( new NameExpr( "?*?" ) );
881 multiply->get_args().push_back( appExpr->get_args().back() );
[ffad73a]882 multiply->get_args().push_back( new NameExpr( sizeofName( baseType ) ) );
[01aeade]883 appExpr->get_args().back() = multiply;
884 } // if
885 } // if
886 return appExpr;
887 } // if
[6c3744e]888 } // if
[01aeade]889 return 0;
890 }
[6c3744e]891
[01aeade]892 Expression *Pass1::mutate( ApplicationExpr *appExpr ) {
[e56cfdb0]893 // std::cerr << "mutate appExpr: ";
894 // for ( TyVarMap::iterator i = scopeTyVars.begin(); i != scopeTyVars.end(); ++i ) {
895 // std::cerr << i->first << " ";
896 // }
897 // std::cerr << "\n";
[01aeade]898 bool oldUseRetval = useRetval;
899 useRetval = false;
900 appExpr->get_function()->acceptMutator( *this );
901 mutateAll( appExpr->get_args(), *this );
902 useRetval = oldUseRetval;
[ae63a18]903
[01aeade]904 assert( ! appExpr->get_function()->get_results().empty() );
905 PointerType *pointer = dynamic_cast< PointerType *>( appExpr->get_function()->get_results().front() );
906 assert( pointer );
907 FunctionType *function = dynamic_cast< FunctionType *>( pointer->get_base() );
908 assert( function );
[ae63a18]909
[01aeade]910 if ( Expression *newExpr = handleIntrinsics( appExpr ) ) {
911 return newExpr;
912 } // if
[ae63a18]913
[01aeade]914 Expression *ret = appExpr;
[ae63a18]915
[01aeade]916 std::list< Expression *>::iterator arg = appExpr->get_args().begin();
917 std::list< Expression *>::iterator paramBegin = appExpr->get_args().begin();
[ae63a18]918
[aadc9a4]919 if ( ReferenceToType *polyType = isPolyRet( function ) ) {
[48ca586]920 ret = addPolyRetParam( appExpr, function, polyType, arg );
[01aeade]921 } else if ( needsAdapter( function, scopeTyVars ) ) {
[e56cfdb0]922 // std::cerr << "needs adapter: ";
923 // for ( TyVarMap::iterator i = scopeTyVars.begin(); i != scopeTyVars.end(); ++i ) {
924 // std::cerr << i->first << " ";
925 // }
926 // std::cerr << "\n";
[01aeade]927 // change the application so it calls the adapter rather than the passed function
928 ret = applyAdapter( appExpr, function, arg, scopeTyVars );
929 } // if
930 arg = appExpr->get_args().begin();
[ae63a18]931
[01aeade]932 TyVarMap exprTyVars;
933 makeTyVarMap( function, exprTyVars );
[ae63a18]934
[01aeade]935 passTypeVars( appExpr, arg, exprTyVars );
936 addInferredParams( appExpr, function, arg, exprTyVars );
[51b73452]937
[01aeade]938 arg = paramBegin;
[ae63a18]939
[01aeade]940 boxParams( appExpr, function, arg, exprTyVars );
[6c3744e]941
[01aeade]942 passAdapters( appExpr, function, exprTyVars );
[6c3744e]943
[01aeade]944 return ret;
945 }
[6c3744e]946
[01aeade]947 Expression *Pass1::mutate( UntypedExpr *expr ) {
[ffad73a]948 if ( ! expr->get_results().empty() && isPolyType( expr->get_results().front(), scopeTyVars, env ) ) {
[01aeade]949 if ( NameExpr *name = dynamic_cast< NameExpr *>( expr->get_function() ) ) {
950 if ( name->get_name() == "*?" ) {
951 Expression *ret = expr->get_args().front();
952 expr->get_args().clear();
953 delete expr;
954 return ret->acceptMutator( *this );
955 } // if
956 } // if
957 } // if
958 return PolyMutator::mutate( expr );
959 }
[6c3744e]960
[01aeade]961 Expression *Pass1::mutate( AddressExpr *addrExpr ) {
962 assert( ! addrExpr->get_arg()->get_results().empty() );
[cf16f94]963
964 bool needs = false;
965 if ( UntypedExpr *expr = dynamic_cast< UntypedExpr *>( addrExpr->get_arg() ) ) {
[5f6c42c]966 if ( ! expr->get_results().empty() && isPolyType( expr->get_results().front(), scopeTyVars, env ) ) {
[cf16f94]967 if ( NameExpr *name = dynamic_cast< NameExpr *>( expr->get_function() ) ) {
968 if ( name->get_name() == "*?" ) {
969 if ( ApplicationExpr * appExpr = dynamic_cast< ApplicationExpr * >( expr->get_args().front() ) ) {
970 assert( ! appExpr->get_function()->get_results().empty() );
971 PointerType *pointer = dynamic_cast< PointerType *>( appExpr->get_function()->get_results().front() );
972 assert( pointer );
973 FunctionType *function = dynamic_cast< FunctionType *>( pointer->get_base() );
974 assert( function );
975 needs = needsAdapter( function, scopeTyVars );
976 } // if
977 } // if
978 } // if
979 } // if
980 } // if
[01aeade]981 addrExpr->set_arg( mutateExpression( addrExpr->get_arg() ) );
[5f6c42c]982 if ( isPolyType( addrExpr->get_arg()->get_results().front(), scopeTyVars, env ) || needs ) {
[01aeade]983 Expression *ret = addrExpr->get_arg();
984 delete ret->get_results().front();
985 ret->get_results().front() = addrExpr->get_results().front()->clone();
986 addrExpr->set_arg( 0 );
987 delete addrExpr;
988 return ret;
989 } else {
990 return addrExpr;
991 } // if
992 }
[6c3744e]993
[b10c9959]994 /// Wraps a function declaration in a new pointer-to-function variable expression
995 VariableExpr *wrapFunctionDecl( DeclarationWithType *functionDecl ) {
996 // line below cloned from FixFunction.cc
997 ObjectDecl *functionObj = new ObjectDecl( functionDecl->get_name(), functionDecl->get_storageClass(), functionDecl->get_linkage(), 0,
998 new PointerType( Type::Qualifiers(), functionDecl->get_type()->clone() ), 0 );
999 functionObj->set_mangleName( functionDecl->get_mangleName() );
1000 return new VariableExpr( functionObj );
1001 }
1002
[cf16f94]1003 Statement * Pass1::mutate( ReturnStmt *returnStmt ) {
1004 if ( retval && returnStmt->get_expr() ) {
1005 assert( ! returnStmt->get_expr()->get_results().empty() );
1006 // ***** Code Removal ***** After introducing a temporary variable for all return expressions, the following code appears superfluous.
1007 // if ( returnStmt->get_expr()->get_results().front()->get_isLvalue() ) {
[ae63a18]1008 // by this point, a cast expr on a polymorphic return value is redundant
[cf16f94]1009 while ( CastExpr *castExpr = dynamic_cast< CastExpr *>( returnStmt->get_expr() ) ) {
1010 returnStmt->set_expr( castExpr->get_arg() );
1011 returnStmt->get_expr()->set_env( castExpr->get_env() );
1012 castExpr->set_env( 0 );
1013 castExpr->set_arg( 0 );
1014 delete castExpr;
[5f6c42c]1015 } //while
[1194734]1016
1017 // find assignment operator for (polymorphic) return type
[b10c9959]1018 ApplicationExpr *assignExpr = 0;
[1194734]1019 if ( TypeInstType *typeInst = dynamic_cast< TypeInstType *>( retval->get_type() ) ) {
[b10c9959]1020 // find assignment operator for type variable
[1194734]1021 std::map< std::string, DeclarationWithType *>::const_iterator assignIter = assignOps.find( typeInst->get_name() );
1022 if ( assignIter == assignOps.end() ) {
1023 throw SemanticError( "Attempt to return dtype or ftype object in ", returnStmt->get_expr() );
1024 } // if
[b10c9959]1025 assignExpr = new ApplicationExpr( new VariableExpr( assignIter->second ) );
[1194734]1026 } else if ( ReferenceToType *refType = dynamic_cast< ReferenceToType *>( retval->get_type() ) ) {
[b10c9959]1027 // find assignment operator for generic type
[1194734]1028 ScopedMap< std::string, DeclarationWithType *>::const_iterator assignIter = scopedAssignOps.find( refType->get_name() );
1029 if ( assignIter == scopedAssignOps.end() ) {
1030 throw SemanticError( "Attempt to return dtype or ftype generic object in ", returnStmt->get_expr() );
1031 }
[b10c9959]1032
1033 // wrap it up in an application expression
[05d47278]1034 DeclarationWithType *functionDecl = assignIter->second;
[b10c9959]1035 assignExpr = new ApplicationExpr( wrapFunctionDecl( functionDecl ) );
1036 assignExpr->set_env( env->clone() );
1037
1038 // find each of its needed secondary assignment operators
1039 std::list< Expression* > &tyParams = refType->get_parameters();
1040 std::list< TypeDecl* > &forallParams = functionDecl->get_type()->get_forall();
1041 std::list< Expression* >::const_iterator tyIt = tyParams.begin();
1042 std::list< TypeDecl* >::const_iterator forallIt = forallParams.begin();
1043 for ( ; tyIt != tyParams.end() && forallIt != forallParams.end(); ++tyIt, ++forallIt ) {
1044 if ( (*forallIt)->get_kind() != TypeDecl::Any ) continue; // skip types with no assign op (ftype/dtype)
1045
1046 std::list< DeclarationWithType* > &asserts = (*forallIt)->get_assertions();
1047 assert( ! asserts.empty() && "Type param needs assignment operator assertion" );
1048 DeclarationWithType *actualDecl = asserts.front();
1049 ReferenceToType *actualType = isAssignment( actualDecl );
1050 assert( actualType && "First assertion of type with assertions should be assignment operator" );
1051 TypeExpr *formalTypeExpr = dynamic_cast< TypeExpr* >( *tyIt );
1052 assert( formalTypeExpr && "type parameters must be type expressions" );
1053 Type *formalType = formalTypeExpr->get_type();
1054 assignExpr->get_env()->add( actualType->get_name(), formalType );
1055
1056 DeclarationWithType *assertAssign = 0;
1057 if ( TypeInstType *formalTypeInstType = dynamic_cast< TypeInstType* >( formalType ) ) {
1058 std::map< std::string, DeclarationWithType *>::const_iterator assertAssignIt = assignOps.find( formalTypeInstType->get_name() );
1059 if ( assertAssignIt == assignOps.end() ) {
1060 throw SemanticError( "No assignment operation found for ", formalTypeInstType );
1061 }
1062 assertAssign = assertAssignIt->second;
1063 //assignExpr->get_env()->add( formalTypeInstType->get_name(), actualType );
1064 } else if ( ReferenceToType *formalReferenceType = dynamic_cast< ReferenceToType* >( formalType ) ) {
1065 ScopedMap< std::string, DeclarationWithType *>::const_iterator assertAssignIt = scopedAssignOps.find( formalReferenceType->get_name() );
1066 if ( assertAssignIt == scopedAssignOps.end() ) {
1067 throw SemanticError( "No assignment operation found for ", formalReferenceType );
1068 }
1069 assertAssign = assertAssignIt->second;
1070 } else assert( false && "returning polymorphic types with non struct/polymorphic parameters not yet supported" );
1071
1072
1073 assignExpr->get_inferParams()[ actualDecl->get_uniqueId() ]
1074 = ParamEntry( assertAssign->get_uniqueId(), assertAssign->get_type()->clone(), actualDecl->get_type()->clone(), wrapFunctionDecl( assertAssign ) );
1075 }
[1194734]1076 }
[b10c9959]1077 assert( assignExpr );
[1194734]1078
1079 // replace return statement with appropriate assignment to out parameter
[cf16f94]1080 Expression *retParm = new NameExpr( retval->get_name() );
1081 retParm->get_results().push_back( new PointerType( Type::Qualifiers(), retval->get_type()->clone() ) );
1082 assignExpr->get_args().push_back( retParm );
1083 assignExpr->get_args().push_back( returnStmt->get_expr() );
1084 stmtsToAdd.push_back( new ExprStmt( noLabels, mutateExpression( assignExpr ) ) );
1085 // } else {
1086 // useRetval = true;
1087 // stmtsToAdd.push_back( new ExprStmt( noLabels, mutateExpression( returnStmt->get_expr() ) ) );
1088 // useRetval = false;
1089 // } // if
1090 returnStmt->set_expr( 0 );
[01aeade]1091 } else {
[cf16f94]1092 returnStmt->set_expr( mutateExpression( returnStmt->get_expr() ) );
[01aeade]1093 } // if
[cf16f94]1094 return returnStmt;
[01aeade]1095 }
[6c3744e]1096
[01aeade]1097 Type * Pass1::mutate( PointerType *pointerType ) {
1098 TyVarMap oldtyVars = scopeTyVars;
1099 makeTyVarMap( pointerType, scopeTyVars );
[ae63a18]1100
[01aeade]1101 Type *ret = Mutator::mutate( pointerType );
[ae63a18]1102
[01aeade]1103 scopeTyVars = oldtyVars;
1104 return ret;
1105 }
[6c3744e]1106
[01aeade]1107 Type * Pass1::mutate( FunctionType *functionType ) {
1108 TyVarMap oldtyVars = scopeTyVars;
1109 makeTyVarMap( functionType, scopeTyVars );
[ae63a18]1110
[01aeade]1111 Type *ret = Mutator::mutate( functionType );
[ae63a18]1112
[01aeade]1113 scopeTyVars = oldtyVars;
1114 return ret;
1115 }
[51b73452]1116
[01aeade]1117 void Pass1::doBeginScope() {
[bdf1954]1118 // push a copy of the current map
[e56cfdb0]1119 adapters.push(adapters.top());
[1194734]1120 scopedAssignOps.beginScope();
[01aeade]1121 }
[b1a6d6b]1122
[01aeade]1123 void Pass1::doEndScope() {
1124 adapters.pop();
[1194734]1125 scopedAssignOps.endScope();
[01aeade]1126 }
[51b73452]1127
1128////////////////////////////////////////// Pass2 ////////////////////////////////////////////////////
1129
[01aeade]1130 void Pass2::addAdapters( FunctionType *functionType ) {
1131 std::list< DeclarationWithType *> &paramList = functionType->get_parameters();
1132 std::list< FunctionType *> functions;
1133 for ( std::list< DeclarationWithType *>::iterator arg = paramList.begin(); arg != paramList.end(); ++arg ) {
1134 Type *orig = (*arg)->get_type();
1135 findAndReplaceFunction( orig, functions, scopeTyVars, needsAdapter );
1136 (*arg)->set_type( orig );
1137 }
1138 std::set< std::string > adaptersDone;
1139 for ( std::list< FunctionType *>::iterator funType = functions.begin(); funType != functions.end(); ++funType ) {
[bdf1954]1140 std::string mangleName = mangleAdapterName( *funType, scopeTyVars );
[01aeade]1141 if ( adaptersDone.find( mangleName ) == adaptersDone.end() ) {
1142 std::string adapterName = makeAdapterName( mangleName );
[68cd1ce]1143 paramList.push_front( new ObjectDecl( adapterName, DeclarationNode::NoStorageClass, LinkageSpec::C, 0, new PointerType( Type::Qualifiers(), makeAdapterType( *funType, scopeTyVars ) ), 0 ) );
[01aeade]1144 adaptersDone.insert( adaptersDone.begin(), mangleName );
1145 }
1146 }
[5f6c42c]1147// deleteAll( functions );
[01aeade]1148 }
[6c3744e]1149
[01aeade]1150 template< typename DeclClass >
1151 DeclClass * Pass2::handleDecl( DeclClass *decl, Type *type ) {
1152 DeclClass *ret = static_cast< DeclClass *>( Mutator::mutate( decl ) );
[6c3744e]1153
[01aeade]1154 return ret;
1155 }
[6c3744e]1156
[01aeade]1157 DeclarationWithType * Pass2::mutate( FunctionDecl *functionDecl ) {
1158 return handleDecl( functionDecl, functionDecl->get_functionType() );
1159 }
[6c3744e]1160
[01aeade]1161 ObjectDecl * Pass2::mutate( ObjectDecl *objectDecl ) {
1162 return handleDecl( objectDecl, objectDecl->get_type() );
1163 }
[6c3744e]1164
[01aeade]1165 TypeDecl * Pass2::mutate( TypeDecl *typeDecl ) {
1166 scopeTyVars[ typeDecl->get_name() ] = typeDecl->get_kind();
1167 if ( typeDecl->get_base() ) {
1168 return handleDecl( typeDecl, typeDecl->get_base() );
1169 } else {
1170 return Mutator::mutate( typeDecl );
1171 }
1172 }
[6c3744e]1173
[01aeade]1174 TypedefDecl * Pass2::mutate( TypedefDecl *typedefDecl ) {
1175 return handleDecl( typedefDecl, typedefDecl->get_base() );
1176 }
[6c3744e]1177
[01aeade]1178 Type * Pass2::mutate( PointerType *pointerType ) {
1179 TyVarMap oldtyVars = scopeTyVars;
1180 makeTyVarMap( pointerType, scopeTyVars );
[ae63a18]1181
[01aeade]1182 Type *ret = Mutator::mutate( pointerType );
[ae63a18]1183
[01aeade]1184 scopeTyVars = oldtyVars;
1185 return ret;
1186 }
[6c3744e]1187
[01aeade]1188 Type *Pass2::mutate( FunctionType *funcType ) {
1189 TyVarMap oldtyVars = scopeTyVars;
1190 makeTyVarMap( funcType, scopeTyVars );
[7754cde]1191
1192 // move polymorphic return type to parameter list
[aadc9a4]1193 if ( isPolyRet( funcType ) ) {
[01aeade]1194 DeclarationWithType *ret = funcType->get_returnVals().front();
1195 ret->set_type( new PointerType( Type::Qualifiers(), ret->get_type() ) );
1196 funcType->get_parameters().push_front( ret );
1197 funcType->get_returnVals().pop_front();
1198 }
[7754cde]1199
1200 // add size/align and assertions for type parameters to parameter list
[01aeade]1201 std::list< DeclarationWithType *>::iterator last = funcType->get_parameters().begin();
1202 std::list< DeclarationWithType *> inferredParams;
[78dd0da]1203 ObjectDecl newObj( "", DeclarationNode::NoStorageClass, LinkageSpec::C, 0, new BasicType( Type::Qualifiers(), BasicType::LongUnsignedInt ), 0 );
[05d47278]1204 ObjectDecl newPtr( "", DeclarationNode::NoStorageClass, LinkageSpec::C, 0,
1205 new PointerType( Type::Qualifiers(), new BasicType( Type::Qualifiers(), BasicType::LongUnsignedInt ) ), 0 );
[f8b961b]1206// ObjectDecl *newFunPtr = new ObjectDecl( "", DeclarationNode::NoStorageClass, LinkageSpec::Cforall, 0, new PointerType( Type::Qualifiers(), new FunctionType( Type::Qualifiers(), true ) ), 0 );
[01aeade]1207 for ( std::list< TypeDecl *>::const_iterator tyParm = funcType->get_forall().begin(); tyParm != funcType->get_forall().end(); ++tyParm ) {
[db0b3ce]1208 ObjectDecl *sizeParm, *alignParm;
1209 // add all size and alignment parameters to parameter list
[01aeade]1210 if ( (*tyParm)->get_kind() == TypeDecl::Any ) {
[78dd0da]1211 TypeInstType parmType( Type::Qualifiers(), (*tyParm)->get_name(), *tyParm );
[ae63a18]1212
[78dd0da]1213 sizeParm = newObj.clone();
1214 sizeParm->set_name( sizeofName( &parmType ) );
[db0b3ce]1215 last = funcType->get_parameters().insert( last, sizeParm );
1216 ++last;
[78dd0da]1217
1218 alignParm = newObj.clone();
1219 alignParm->set_name( alignofName( &parmType ) );
[db0b3ce]1220 last = funcType->get_parameters().insert( last, alignParm );
[01aeade]1221 ++last;
1222 }
[e56cfdb0]1223 // move all assertions into parameter list
[01aeade]1224 for ( std::list< DeclarationWithType *>::iterator assert = (*tyParm)->get_assertions().begin(); assert != (*tyParm)->get_assertions().end(); ++assert ) {
[f8b961b]1225// *assert = (*assert)->acceptMutator( *this );
[01aeade]1226 inferredParams.push_back( *assert );
1227 }
1228 (*tyParm)->get_assertions().clear();
1229 }
[7754cde]1230
1231 // add size/align for generic types to parameter list
[b18b0b5]1232 std::set< std::string > seenTypes; // sizeofName for generic types we've seen
[7754cde]1233 for ( std::list< DeclarationWithType* >::const_iterator fnParm = last; fnParm != funcType->get_parameters().end(); ++fnParm ) {
[32805db]1234 Type *polyBase = hasPolyBase( (*fnParm)->get_type(), scopeTyVars );
1235 if ( polyBase && ! dynamic_cast< TypeInstType* >( polyBase ) ) {
1236 std::string sizeName = sizeofName( polyBase );
[7754cde]1237 if ( seenTypes.count( sizeName ) ) continue;
[ae63a18]1238
[05d47278]1239 ObjectDecl *sizeParm, *alignParm, *offsetParm;
[7754cde]1240 sizeParm = newObj.clone();
1241 sizeParm->set_name( sizeName );
1242 last = funcType->get_parameters().insert( last, sizeParm );
1243 ++last;
1244
1245 alignParm = newObj.clone();
[32805db]1246 alignParm->set_name( alignofName( polyBase ) );
[7754cde]1247 last = funcType->get_parameters().insert( last, alignParm );
1248 ++last;
1249
[32805db]1250 if ( dynamic_cast< StructInstType* >( polyBase ) ) {
[05d47278]1251 offsetParm = newPtr.clone();
[32805db]1252 offsetParm->set_name( offsetofName( polyBase ) );
[05d47278]1253 last = funcType->get_parameters().insert( last, offsetParm );
1254 ++last;
1255 }
1256
[7754cde]1257 seenTypes.insert( sizeName );
1258 }
1259 }
1260
1261 // splice assertion parameters into parameter list
[01aeade]1262 funcType->get_parameters().splice( last, inferredParams );
1263 addAdapters( funcType );
1264 mutateAll( funcType->get_returnVals(), *this );
1265 mutateAll( funcType->get_parameters(), *this );
[ae63a18]1266
[01aeade]1267 scopeTyVars = oldtyVars;
1268 return funcType;
1269 }
[51b73452]1270
[05d47278]1271////////////////////////////////////////// MemberExprFixer ////////////////////////////////////////////////////
[51b73452]1272
[01aeade]1273 template< typename DeclClass >
[05d47278]1274 DeclClass * MemberExprFixer::handleDecl( DeclClass *decl, Type *type ) {
[01aeade]1275 TyVarMap oldtyVars = scopeTyVars;
1276 makeTyVarMap( type, scopeTyVars );
[ae63a18]1277
[01aeade]1278 DeclClass *ret = static_cast< DeclClass *>( Mutator::mutate( decl ) );
[6c3744e]1279
[01aeade]1280 scopeTyVars = oldtyVars;
1281 return ret;
1282 }
[6c3744e]1283
[05d47278]1284 ObjectDecl * MemberExprFixer::mutate( ObjectDecl *objectDecl ) {
[01aeade]1285 return handleDecl( objectDecl, objectDecl->get_type() );
1286 }
[6c3744e]1287
[05d47278]1288 DeclarationWithType * MemberExprFixer::mutate( FunctionDecl *functionDecl ) {
[01aeade]1289 return handleDecl( functionDecl, functionDecl->get_functionType() );
1290 }
[6c3744e]1291
[05d47278]1292 TypedefDecl * MemberExprFixer::mutate( TypedefDecl *typedefDecl ) {
[01aeade]1293 return handleDecl( typedefDecl, typedefDecl->get_base() );
1294 }
[6c3744e]1295
[05d47278]1296 TypeDecl * MemberExprFixer::mutate( TypeDecl *typeDecl ) {
[01aeade]1297 scopeTyVars[ typeDecl->get_name() ] = typeDecl->get_kind();
1298 return Mutator::mutate( typeDecl );
1299 }
[51b73452]1300
[05d47278]1301 Type * MemberExprFixer::mutate( PointerType *pointerType ) {
[01aeade]1302 TyVarMap oldtyVars = scopeTyVars;
1303 makeTyVarMap( pointerType, scopeTyVars );
[ae63a18]1304
[01aeade]1305 Type *ret = Mutator::mutate( pointerType );
[ae63a18]1306
[01aeade]1307 scopeTyVars = oldtyVars;
1308 return ret;
1309 }
[6c3744e]1310
[05d47278]1311 Type * MemberExprFixer::mutate( FunctionType *functionType ) {
[01aeade]1312 TyVarMap oldtyVars = scopeTyVars;
1313 makeTyVarMap( functionType, scopeTyVars );
[ae63a18]1314
[01aeade]1315 Type *ret = Mutator::mutate( functionType );
[ae63a18]1316
[01aeade]1317 scopeTyVars = oldtyVars;
1318 return ret;
[6c3744e]1319 }
[51b73452]1320
[05d47278]1321 Statement *MemberExprFixer::mutate( DeclStmt *declStmt ) {
[01aeade]1322 if ( ObjectDecl *objectDecl = dynamic_cast< ObjectDecl *>( declStmt->get_decl() ) ) {
[ffad73a]1323 if ( isPolyType( objectDecl->get_type(), scopeTyVars ) ) {
[e01559c]1324 // change initialization of a polymorphic value object
1325 // to allocate storage with alloca
[ffad73a]1326 Type *declType = objectDecl->get_type();
[01aeade]1327 UntypedExpr *alloc = new UntypedExpr( new NameExpr( "__builtin_alloca" ) );
[ffad73a]1328 alloc->get_args().push_back( new NameExpr( sizeofName( declType ) ) );
[e01559c]1329
1330 delete objectDecl->get_init();
1331
1332 std::list<Expression*> designators;
1333 objectDecl->set_init( new SingleInit( alloc, designators ) );
[01aeade]1334 }
1335 }
1336 return Mutator::mutate( declStmt );
1337 }
[05d47278]1338
[2a4b088]1339 /// Finds the member in the base list that matches the given declaration; returns its index, or -1 if not present
1340 long findMember( DeclarationWithType *memberDecl, std::list< Declaration* > &baseDecls ) {
1341 long i = 0;
1342 for(std::list< Declaration* >::const_iterator decl = baseDecls.begin(); decl != baseDecls.end(); ++decl, ++i ) {
1343 if ( memberDecl->get_name() != (*decl)->get_name() ) continue;
1344
1345 if ( DeclarationWithType *declWithType = dynamic_cast< DeclarationWithType* >( *decl ) ) {
[bed4d37c]1346 if ( memberDecl->get_mangleName().empty() || declWithType->get_mangleName().empty()
1347 || memberDecl->get_mangleName() == declWithType->get_mangleName() ) return i;
[2a4b088]1348 else continue;
1349 } else return i;
1350 }
1351 return -1;
1352 }
1353
1354 /// Returns an index expression into the offset array for a type
1355 Expression *makeOffsetIndex( Type *objectType, long i ) {
1356 std::stringstream offset_namer;
1357 offset_namer << i;
1358 ConstantExpr *fieldIndex = new ConstantExpr( Constant( new BasicType( Type::Qualifiers(), BasicType::LongUnsignedInt ), offset_namer.str() ) );
1359 UntypedExpr *fieldOffset = new UntypedExpr( new NameExpr( "?[?]" ) );
1360 fieldOffset->get_args().push_back( new NameExpr( offsetofName( objectType ) ) );
1361 fieldOffset->get_args().push_back( fieldIndex );
1362 return fieldOffset;
1363 }
1364
1365 /// Returns an expression dereferenced n times
1366 Expression *makeDerefdVar( Expression *derefdVar, long n ) {
1367 for ( int i = 1; i < n; ++i ) {
1368 UntypedExpr *derefExpr = new UntypedExpr( new NameExpr( "*?" ) );
1369 derefExpr->get_args().push_back( derefdVar );
1370 derefdVar = derefExpr;
1371 }
1372 return derefdVar;
1373 }
1374
[05d47278]1375 Expression *MemberExprFixer::mutate( MemberExpr *memberExpr ) {
1376 // mutate, exiting early if no longer MemberExpr
1377 Expression *expr = Mutator::mutate( memberExpr );
1378 memberExpr = dynamic_cast< MemberExpr* >( expr );
1379 if ( ! memberExpr ) return expr;
1380
1381 // get declaration for base struct, exiting early if not found
[8488c715]1382 int varDepth;
1383 VariableExpr *varExpr = getBaseVar( memberExpr->get_aggregate(), &varDepth );
[05d47278]1384 if ( ! varExpr ) return memberExpr;
1385 ObjectDecl *objectDecl = dynamic_cast< ObjectDecl* >( varExpr->get_var() );
1386 if ( ! objectDecl ) return memberExpr;
1387
1388 // only mutate member expressions for polymorphic types
[8488c715]1389 int tyDepth;
1390 Type *objectType = hasPolyBase( objectDecl->get_type(), scopeTyVars, &tyDepth );
[05d47278]1391 if ( ! objectType ) return memberExpr;
1392
1393 if ( StructInstType *structType = dynamic_cast< StructInstType* >( objectType ) ) {
[2a4b088]1394 // look up offset index
1395 long i = findMember( memberExpr->get_member(), structType->get_baseStruct()->get_members() );
1396 if ( i == -1 ) return memberExpr;
[05d47278]1397
[2a4b088]1398 // replace member expression with pointer to base plus offset
1399 UntypedExpr *fieldLoc = new UntypedExpr( new NameExpr( "?+?" ) );
1400 fieldLoc->get_args().push_back( makeDerefdVar( varExpr->clone(), varDepth ) );
1401 fieldLoc->get_args().push_back( makeOffsetIndex( objectType, i ) );
[05d47278]1402
[2a4b088]1403 delete memberExpr;
1404 return fieldLoc;
[98735ef]1405 } else if ( dynamic_cast< UnionInstType* >( objectType ) ) {
[2a4b088]1406 // union members are all at offset zero, so build appropriately-dereferenced variable
1407 Expression *derefdVar = makeDerefdVar( varExpr->clone(), varDepth );
1408 delete memberExpr;
1409 return derefdVar;
1410 } else return memberExpr;
1411 }
[05d47278]1412
[2a4b088]1413 Expression *MemberExprFixer::mutate( OffsetofExpr *offsetofExpr ) {
1414 // mutate, exiting early if no longer OffsetofExpr
1415 Expression *expr = Mutator::mutate( offsetofExpr );
1416 offsetofExpr = dynamic_cast< OffsetofExpr* >( expr );
1417 if ( ! offsetofExpr ) return expr;
1418
1419 // only mutate expressions for polymorphic structs/unions
1420 Type *ty = isPolyType( offsetofExpr->get_type(), scopeTyVars );
1421 if ( ! ty ) return offsetofExpr;
1422
1423 if ( StructInstType *structType = dynamic_cast< StructInstType* >( ty ) ) {
1424 // replace offsetof expression by index into offset array
1425 long i = findMember( offsetofExpr->get_member(), structType->get_baseStruct()->get_members() );
1426 if ( i == -1 ) return offsetofExpr;
1427
1428 Expression *offsetInd = makeOffsetIndex( ty, i );
1429 delete offsetofExpr;
1430 return offsetInd;
1431 } else if ( UnionInstType *unionType = dynamic_cast< UnionInstType* >( ty ) ) {
1432 // all union members are at offset zero
1433 delete offsetofExpr;
1434 return new ConstantExpr( Constant( new BasicType( Type::Qualifiers(), BasicType::LongUnsignedInt ), std::string("0") ) );
1435 } else return offsetofExpr;
[05d47278]1436 }
1437
1438////////////////////////////////////////// Pass3 ////////////////////////////////////////////////////
1439
1440 template< typename DeclClass >
1441 DeclClass * Pass3::handleDecl( DeclClass *decl, Type *type ) {
1442 TyVarMap oldtyVars = scopeTyVars;
1443 makeTyVarMap( type, scopeTyVars );
1444
1445 DeclClass *ret = static_cast< DeclClass *>( Mutator::mutate( decl ) );
1446 ScrubTyVars::scrub( decl, scopeTyVars );
1447
1448 scopeTyVars = oldtyVars;
1449 return ret;
1450 }
1451
1452 ObjectDecl * Pass3::mutate( ObjectDecl *objectDecl ) {
1453 return handleDecl( objectDecl, objectDecl->get_type() );
1454 }
1455
1456 DeclarationWithType * Pass3::mutate( FunctionDecl *functionDecl ) {
1457 return handleDecl( functionDecl, functionDecl->get_functionType() );
1458 }
1459
1460 TypedefDecl * Pass3::mutate( TypedefDecl *typedefDecl ) {
1461 return handleDecl( typedefDecl, typedefDecl->get_base() );
1462 }
1463
1464 TypeDecl * Pass3::mutate( TypeDecl *typeDecl ) {
1465// Initializer *init = 0;
1466// std::list< Expression *> designators;
1467// scopeTyVars[ typeDecl->get_name() ] = typeDecl->get_kind();
1468// if ( typeDecl->get_base() ) {
1469// init = new SimpleInit( new SizeofExpr( handleDecl( typeDecl, typeDecl->get_base() ) ), designators );
1470// }
1471// return new ObjectDecl( typeDecl->get_name(), Declaration::Extern, LinkageSpec::C, 0, new BasicType( Type::Qualifiers(), BasicType::UnsignedInt ), init );
1472
1473 scopeTyVars[ typeDecl->get_name() ] = typeDecl->get_kind();
1474 return Mutator::mutate( typeDecl );
1475 }
1476
1477 Type * Pass3::mutate( PointerType *pointerType ) {
1478 TyVarMap oldtyVars = scopeTyVars;
1479 makeTyVarMap( pointerType, scopeTyVars );
1480
1481 Type *ret = Mutator::mutate( pointerType );
1482
1483 scopeTyVars = oldtyVars;
1484 return ret;
1485 }
1486
1487 Type * Pass3::mutate( FunctionType *functionType ) {
1488 TyVarMap oldtyVars = scopeTyVars;
1489 makeTyVarMap( functionType, scopeTyVars );
1490
1491 Type *ret = Mutator::mutate( functionType );
1492
1493 scopeTyVars = oldtyVars;
1494 return ret;
1495 }
[01aeade]1496 } // anonymous namespace
[51b73452]1497} // namespace GenPoly
[01aeade]1498
[51587aa]1499// Local Variables: //
1500// tab-width: 4 //
1501// mode: c++ //
1502// compile-command: "make install" //
1503// End: //
Note: See TracBrowser for help on using the repository browser.