source: src/GenPoly/Box.cc@ bd91e2a

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 with_gc
Last change on this file since bd91e2a was bd91e2a, checked in by Aaron Moss <a3moss@…>, 10 years ago

Properly clone types in layout function generation

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