source: src/InitTweak/FixInit.cc@ 1132b62

ADT aaron-thesis arm-eh ast-experimental cleanup-dtors deferred_resn demangler enum forall-pointer-decay jacob/cs343-translation jenkins-sandbox new-ast new-ast-unique-expr new-env no_list persistent-indexer pthread-emulation qualifiedEnum resolv-new stuck-waitfor-destruct with_gc
Last change on this file since 1132b62 was 1132b62, checked in by Rob Schluntz <rschlunt@…>, 9 years ago

copy construct tuple function arguments, and destruct tuple function results

  • Property mode set to 100644
File size: 42.6 KB
RevLine 
[71f4e4f]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// FixInit.h --
8//
9// Author : Rob Schluntz
10// Created On : Wed Jan 13 16:29:30 2016
[adcc065]11// Last Modified By : Peter A. Buhr
[4e06c1e]12// Last Modified On : Tue Jul 12 17:41:15 2016
13// Update Count : 34
[71f4e4f]14//
15
16#include <stack>
17#include <list>
[c2931ea]18#include <iterator>
19#include <algorithm>
[7b3f66b]20#include "InitTweak.h"
[6cf27a07]21#include "FixInit.h"
22#include "FixGlobalInit.h"
[db4ecc5]23#include "ResolvExpr/Resolver.h"
[845cedc]24#include "ResolvExpr/typeops.h"
[71f4e4f]25#include "SynTree/Declaration.h"
26#include "SynTree/Type.h"
27#include "SynTree/Expression.h"
[f9cebb5]28#include "SynTree/Attribute.h"
[71f4e4f]29#include "SynTree/Statement.h"
30#include "SynTree/Initializer.h"
31#include "SynTree/Mutator.h"
[db4ecc5]32#include "SymTab/Indexer.h"
[c8dfcd3]33#include "SymTab/Autogen.h"
[71f4e4f]34#include "GenPoly/PolyMutator.h"
[b6fe7e6]35#include "GenPoly/DeclMutator.h"
[c2931ea]36#include "SynTree/AddStmtVisitor.h"
[79970ed]37#include "CodeGen/GenType.h" // for warnings
[71f4e4f]38
[845cedc]39bool ctordtorp = false;
[c2931ea]40bool ctorp = false;
41bool cpctorp = false;
[e39aa0f]42bool dtorp = false;
[845cedc]43#define PRINT( text ) if ( ctordtorp ) { text }
[c2931ea]44#define CP_CTOR_PRINT( text ) if ( ctordtorp || cpctorp ) { text }
45#define DTOR_PRINT( text ) if ( ctordtorp || dtorp ) { text }
[845cedc]46
[71f4e4f]47namespace InitTweak {
48 namespace {
49 const std::list<Label> noLabels;
[e0323a2]50 const std::list<Expression*> noDesignators;
[71f4e4f]51
[c2931ea]52 class InsertImplicitCalls : public GenPoly::PolyMutator {
53 public:
[adcc065]54 /// wrap function application expressions as ImplicitCopyCtorExpr nodes so that it is easy to identify which
55 /// function calls need their parameters to be copy constructed
[c2931ea]56 static void insert( std::list< Declaration * > & translationUnit );
57
58 virtual Expression * mutate( ApplicationExpr * appExpr );
59 };
60
61 class ResolveCopyCtors : public SymTab::Indexer {
62 public:
[adcc065]63 /// generate temporary ObjectDecls for each argument and return value of each ImplicitCopyCtorExpr,
64 /// generate/resolve copy construction expressions for each, and generate/resolve destructors for both
65 /// arguments and return value temporaries
[c2931ea]66 static void resolveImplicitCalls( std::list< Declaration * > & translationUnit );
67
68 virtual void visit( ImplicitCopyCtorExpr * impCpCtorExpr );
69
70 /// create and resolve ctor/dtor expression: fname(var, [cpArg])
71 ApplicationExpr * makeCtorDtor( const std::string & fname, ObjectDecl * var, Expression * cpArg = NULL );
[1132b62]72 ApplicationExpr * makeCtorDtor( const std::string & fname, Expression * thisArg, Expression * cpArg = NULL );
[c2931ea]73 /// true if type does not need to be copy constructed to ensure correctness
[1132b62]74 bool skipCopyConstruct( Type * type );
75 void copyConstructArg( Expression *& arg, ImplicitCopyCtorExpr * impCpCtorExpr );
76 void destructRet( Expression * ret, ImplicitCopyCtorExpr * impCpCtorExpr );
[c2931ea]77 private:
78 TypeSubstitution * env;
79 };
80
81 /// collects constructed object decls - used as a base class
82 class ObjDeclCollector : public AddStmtVisitor {
83 public:
84 typedef AddStmtVisitor Parent;
85 using Parent::visit;
86 typedef std::set< ObjectDecl * > ObjectSet;
87 virtual void visit( CompoundStmt *compoundStmt );
88 virtual void visit( DeclStmt *stmt );
89 protected:
90 ObjectSet curVars;
91 };
92
[6cf27a07]93 // debug
[c2931ea]94 struct printSet {
95 typedef ObjDeclCollector::ObjectSet ObjectSet;
96 printSet( const ObjectSet & objs ) : objs( objs ) {}
97 const ObjectSet & objs;
98 };
99 std::ostream & operator<<( std::ostream & out, const printSet & set) {
100 out << "{ ";
101 for ( ObjectDecl * obj : set.objs ) {
102 out << obj->get_name() << ", " ;
[adcc065]103 } // for
[c2931ea]104 out << " }";
105 return out;
106 }
107
108 class LabelFinder : public ObjDeclCollector {
109 public:
110 typedef ObjDeclCollector Parent;
111 typedef std::map< Label, ObjectSet > LabelMap;
112 // map of Label -> live variables at that label
113 LabelMap vars;
114
115 void handleStmt( Statement * stmt );
116
117 // xxx - This needs to be done better.
[adcc065]118 // allow some generalization among different kinds of nodes with with similar parentage (e.g. all
119 // expressions, all statements, etc.) important to have this to provide a single entry point so that as new
120 // subclasses are added, there is only one place that the code has to be updated, rather than ensure that
121 // every specialized class knows about every new kind of statement that might be added.
[c2931ea]122 virtual void visit( CompoundStmt *stmt ) { handleStmt( stmt ); return Parent::visit( stmt ); }
123 virtual void visit( ExprStmt *stmt ) { handleStmt( stmt ); return Parent::visit( stmt ); }
124 virtual void visit( AsmStmt *stmt ) { handleStmt( stmt ); return Parent::visit( stmt ); }
125 virtual void visit( IfStmt *stmt ) { handleStmt( stmt ); return Parent::visit( stmt ); }
126 virtual void visit( WhileStmt *stmt ) { handleStmt( stmt ); return Parent::visit( stmt ); }
127 virtual void visit( ForStmt *stmt ) { handleStmt( stmt ); return Parent::visit( stmt ); }
128 virtual void visit( SwitchStmt *stmt ) { handleStmt( stmt ); return Parent::visit( stmt ); }
129 virtual void visit( CaseStmt *stmt ) { handleStmt( stmt ); return Parent::visit( stmt ); }
130 virtual void visit( BranchStmt *stmt ) { handleStmt( stmt ); return Parent::visit( stmt ); }
131 virtual void visit( ReturnStmt *stmt ) { handleStmt( stmt ); return Parent::visit( stmt ); }
132 virtual void visit( TryStmt *stmt ) { handleStmt( stmt ); return Parent::visit( stmt ); }
133 virtual void visit( CatchStmt *stmt ) { handleStmt( stmt ); return Parent::visit( stmt ); }
134 virtual void visit( FinallyStmt *stmt ) { handleStmt( stmt ); return Parent::visit( stmt ); }
135 virtual void visit( NullStmt *stmt ) { handleStmt( stmt ); return Parent::visit( stmt ); }
136 virtual void visit( DeclStmt *stmt ) { handleStmt( stmt ); return Parent::visit( stmt ); }
137 virtual void visit( ImplicitCtorDtorStmt *stmt ) { handleStmt( stmt ); return Parent::visit( stmt ); }
138 };
139
140 class InsertDtors : public ObjDeclCollector {
141 public:
[adcc065]142 /// insert destructor calls at the appropriate places. must happen before CtorInit nodes are removed
143 /// (currently by FixInit)
[c2931ea]144 static void insert( std::list< Declaration * > & translationUnit );
145
146 typedef ObjDeclCollector Parent;
147 typedef std::list< ObjectDecl * > OrderedDecls;
148 typedef std::list< OrderedDecls > OrderedDeclsStack;
149
150 InsertDtors( LabelFinder & finder ) : labelVars( finder.vars ) {}
151
152 virtual void visit( ObjectDecl * objDecl );
153
154 virtual void visit( CompoundStmt * compoundStmt );
155 virtual void visit( ReturnStmt * returnStmt );
156 virtual void visit( BranchStmt * stmt );
157 private:
158 void handleGoto( BranchStmt * stmt );
159
160 LabelFinder::LabelMap & labelVars;
161 OrderedDeclsStack reverseDeclOrder;
162 };
163
164 class FixInit : public GenPoly::PolyMutator {
165 public:
166 /// expand each object declaration to use its constructor after it is declared.
167 static void fixInitializers( std::list< Declaration * > &translationUnit );
168
169 virtual DeclarationWithType * mutate( ObjectDecl *objDecl );
[72e9222]170
171 std::list< Declaration * > staticDtorDecls;
[c2931ea]172 };
173
174 class FixCopyCtors : public GenPoly::PolyMutator {
175 public:
[adcc065]176 /// expand ImplicitCopyCtorExpr nodes into the temporary declarations, copy constructors, call expression,
177 /// and destructors
[c2931ea]178 static void fixCopyCtors( std::list< Declaration * > &translationUnit );
179
180 virtual Expression * mutate( ImplicitCopyCtorExpr * impCpCtorExpr );
181 };
[79970ed]182
[c8dfcd3]183 class GenStructMemberCalls : public SymTab::Indexer {
[79970ed]184 public:
[c8dfcd3]185 typedef Indexer Parent;
186 /// generate default/copy ctor and dtor calls for user-defined struct ctor/dtors
187 /// for any member that is missing a corresponding ctor/dtor call.
188 /// error if a member is used before constructed
189 static void generate( std::list< Declaration * > & translationUnit );
[79970ed]190
191 virtual void visit( FunctionDecl * funcDecl );
192
193 virtual void visit( MemberExpr * memberExpr );
194 virtual void visit( ApplicationExpr * appExpr );
195
[3906301]196 SemanticError errors;
[79970ed]197 private:
198 void handleFirstParam( Expression * firstParam );
[3906301]199 template< typename... Params >
200 void emit( const Params &... params );
[79970ed]201
202 FunctionDecl * function = 0;
[c8dfcd3]203 std::set< DeclarationWithType * > unhandled, usedUninit;
[79970ed]204 ObjectDecl * thisParam = 0;
[c8dfcd3]205 bool isCtor = false; // true if current function is a constructor
[44f6341]206 StructDecl * structDecl = 0;
[c8dfcd3]207 };
208
209 // very simple resolver-like mutator class - used to
210 // resolve UntypedExprs that are found within newly
211 // generated constructor/destructor calls
212 class MutatingResolver : public Mutator {
213 public:
214 MutatingResolver( SymTab::Indexer & indexer ) : indexer( indexer ) {}
215
216 virtual DeclarationWithType* mutate( ObjectDecl *objectDecl );
217
218 virtual Expression* mutate( UntypedExpr *untypedExpr );
219 private:
220 SymTab::Indexer & indexer;
[79970ed]221 };
[b6fe7e6]222
223 class FixCtorExprs : public GenPoly::DeclMutator {
224 public:
225 /// expands ConstructorExpr nodes into comma expressions, using a temporary for the first argument
226 static void fix( std::list< Declaration * > & translationUnit );
227
228 virtual Expression * mutate( ConstructorExpr * ctorExpr );
229 };
[c2931ea]230 } // namespace
[db4ecc5]231
[6cf27a07]232 void fix( std::list< Declaration * > & translationUnit, const std::string & filename, bool inLibrary ) {
233 // fixes ConstructorInit for global variables. should happen before fixInitializers.
234 InitTweak::fixGlobalInit( translationUnit, filename, inLibrary );
235
[b6fe7e6]236
[db4ecc5]237 InsertImplicitCalls::insert( translationUnit );
238 ResolveCopyCtors::resolveImplicitCalls( translationUnit );
[c2931ea]239 InsertDtors::insert( translationUnit );
[71f4e4f]240 FixInit::fixInitializers( translationUnit );
[c2931ea]241
[db4ecc5]242 // FixCopyCtors must happen after FixInit, so that destructors are placed correctly
243 FixCopyCtors::fixCopyCtors( translationUnit );
[79970ed]244
[c8dfcd3]245 GenStructMemberCalls::generate( translationUnit );
[b6fe7e6]246 // xxx - ctor expansion currently has to be after FixCopyCtors, because there is currently a
247 // hack in the way untyped assignments are generated, where the first argument cannot have
248 // its address taken because of the way codegeneration handles UntypedExpr vs. ApplicationExpr.
249 // Thus such assignment exprs must never pushed through expression resolution (and thus should
250 // not go through the FixCopyCtors pass), otherwise they will fail -- guaranteed.
251 // Also needs to happen after GenStructMemberCalls, since otherwise member constructors exprs
252 // don't look right, and a member can be constructed more than once.
253 FixCtorExprs::fix( translationUnit );
[db4ecc5]254 }
255
[c2931ea]256 namespace {
257 void InsertImplicitCalls::insert( std::list< Declaration * > & translationUnit ) {
258 InsertImplicitCalls inserter;
259 mutateAll( translationUnit, inserter );
260 }
[db4ecc5]261
[c2931ea]262 void ResolveCopyCtors::resolveImplicitCalls( std::list< Declaration * > & translationUnit ) {
263 ResolveCopyCtors resolver;
264 acceptAll( translationUnit, resolver );
265 }
[71f4e4f]266
[c2931ea]267 void FixInit::fixInitializers( std::list< Declaration * > & translationUnit ) {
268 FixInit fixer;
[72e9222]269
270 // can't use mutateAll, because need to insert declarations at top-level
271 // can't use DeclMutator, because sometimes need to insert IfStmt, etc.
272 SemanticError errors;
273 for ( std::list< Declaration * >::iterator i = translationUnit.begin(); i != translationUnit.end(); ++i ) {
274 try {
275 *i = maybeMutate( *i, fixer );
[f9cebb5]276 translationUnit.splice( i, fixer.staticDtorDecls );
[72e9222]277 } catch( SemanticError &e ) {
278 errors.append( e );
279 } // try
280 } // for
281 if ( ! errors.isEmpty() ) {
282 throw errors;
283 } // if
[c2931ea]284 }
[71f4e4f]285
[c2931ea]286 void InsertDtors::insert( std::list< Declaration * > & translationUnit ) {
287 LabelFinder finder;
288 InsertDtors inserter( finder );
289 acceptAll( translationUnit, finder );
290 acceptAll( translationUnit, inserter );
291 }
292
293 void FixCopyCtors::fixCopyCtors( std::list< Declaration * > & translationUnit ) {
294 FixCopyCtors fixer;
295 mutateAll( translationUnit, fixer );
296 }
[db4ecc5]297
[c8dfcd3]298 void GenStructMemberCalls::generate( std::list< Declaration * > & translationUnit ) {
299 GenStructMemberCalls warner;
300 acceptAll( translationUnit, warner );
[3906301]301
[c8dfcd3]302 // visitor doesn't throw so that it can collect all errors
303 if ( ! warner.errors.isEmpty() ) {
304 throw warner.errors;
[79970ed]305 }
306 }
307
[b6fe7e6]308 void FixCtorExprs::fix( std::list< Declaration * > & translationUnit ) {
309 FixCtorExprs fixer;
310 fixer.mutateDeclarationList( translationUnit );
311 }
312
[c2931ea]313 Expression * InsertImplicitCalls::mutate( ApplicationExpr * appExpr ) {
314 appExpr = dynamic_cast< ApplicationExpr * >( Mutator::mutate( appExpr ) );
315 assert( appExpr );
316
317 if ( VariableExpr * function = dynamic_cast< VariableExpr * > ( appExpr->get_function() ) ) {
318 if ( function->get_var()->get_linkage() == LinkageSpec::Intrinsic ) {
319 // optimization: don't need to copy construct in order to call intrinsic functions
320 return appExpr;
321 } else if ( DeclarationWithType * funcDecl = dynamic_cast< DeclarationWithType * > ( function->get_var() ) ) {
322 FunctionType * ftype = dynamic_cast< FunctionType * >( GenPoly::getFunctionType( funcDecl->get_type() ) );
323 assert( ftype );
[79970ed]324 if ( (isConstructor( funcDecl->get_name() ) || funcDecl->get_name() == "?=?") && ftype->get_parameters().size() == 2 ) {
[c2931ea]325 Type * t1 = ftype->get_parameters().front()->get_type();
326 Type * t2 = ftype->get_parameters().back()->get_type();
327 PointerType * ptrType = dynamic_cast< PointerType * > ( t1 );
328 assert( ptrType );
329
330 if ( ResolvExpr::typesCompatible( ptrType->get_base(), t2, SymTab::Indexer() ) ) {
331 // optimization: don't need to copy construct in order to call a copy constructor or
332 // assignment operator
333 return appExpr;
[adcc065]334 } // if
[79970ed]335 } else if ( isDestructor( funcDecl->get_name() ) ) {
[c2931ea]336 // correctness: never copy construct arguments to a destructor
[845cedc]337 return appExpr;
[adcc065]338 } // if
339 } // if
340 } // if
[c2931ea]341 CP_CTOR_PRINT( std::cerr << "InsertImplicitCalls: adding a wrapper " << appExpr << std::endl; )
342
343 // wrap each function call so that it is easy to identify nodes that have to be copy constructed
344 ImplicitCopyCtorExpr * expr = new ImplicitCopyCtorExpr( appExpr );
345 // save the type substitution onto the new node so that it is easy to find.
346 // Ensure it is not deleted with the ImplicitCopyCtorExpr by removing it before deletion.
347 // The substitution is needed to obtain the type of temporary variables so that copy constructor
348 // calls can be resolved. Normally this is what PolyMutator is for, but the pass that resolves
349 // copy constructor calls must be an Indexer. We could alternatively make a PolyIndexer which
350 // saves the environment, or compute the types of temporaries here, but it's much simpler to
351 // save the environment here, and more cohesive to compute temporary variables and resolve copy
352 // constructor calls together.
353 assert( env );
354 expr->set_env( env );
355 return expr;
[db4ecc5]356 }
357
[c2931ea]358 bool ResolveCopyCtors::skipCopyConstruct( Type * type ) {
359 return dynamic_cast< VarArgsType * >( type ) || GenPoly::getFunctionType( type );
360 }
361
362 ApplicationExpr * ResolveCopyCtors::makeCtorDtor( const std::string & fname, ObjectDecl * var, Expression * cpArg ) {
363 assert( var );
[1132b62]364 return makeCtorDtor( fname, new AddressExpr( new VariableExpr( var ) ), cpArg );
365 }
366
367 ApplicationExpr * ResolveCopyCtors::makeCtorDtor( const std::string & fname, Expression * thisArg, Expression * cpArg ) {
368 assert( thisArg );
[c2931ea]369 UntypedExpr * untyped = new UntypedExpr( new NameExpr( fname ) );
[1132b62]370 untyped->get_args().push_back( thisArg );
[03b812d2]371 if (cpArg) untyped->get_args().push_back( cpArg->clone() );
[c2931ea]372
373 // resolve copy constructor
[adcc065]374 // should only be one alternative for copy ctor and dtor expressions, since all arguments are fixed
375 // (VariableExpr and already resolved expression)
[c2931ea]376 CP_CTOR_PRINT( std::cerr << "ResolvingCtorDtor " << untyped << std::endl; )
377 ApplicationExpr * resolved = dynamic_cast< ApplicationExpr * >( ResolvExpr::findVoidExpression( untyped, *this ) );
378 if ( resolved->get_env() ) {
379 env->add( *resolved->get_env() );
[adcc065]380 } // if
[cf18eea]381
[c2931ea]382 assert( resolved );
383 delete untyped;
384 return resolved;
[540de412]385 }
[db4ecc5]386
[1132b62]387 void ResolveCopyCtors::copyConstructArg( Expression *& arg, ImplicitCopyCtorExpr * impCpCtorExpr ) {
[c2931ea]388 static UniqueName tempNamer("_tmp_cp");
[1132b62]389 CP_CTOR_PRINT( std::cerr << "Type Substitution: " << *impCpCtorExpr->get_env() << std::endl; )
390 assert( arg->has_result() );
391 Type * result = arg->get_result();
392 if ( skipCopyConstruct( result ) ) return; // skip certain non-copyable types
393
394 if ( TupleExpr * tupleExpr = dynamic_cast< TupleExpr * >( arg ) ) {
395 for ( Expression * & expr : tupleExpr->get_exprs() ) {
396 copyConstructArg( expr, impCpCtorExpr );
397 }
398 return;
399 }
400
401 // type may involve type variables, so apply type substitution to get temporary variable's actual type
402 result = result->clone();
403 impCpCtorExpr->get_env()->apply( result );
404 ObjectDecl * tmp = new ObjectDecl( tempNamer.newName(), DeclarationNode::NoStorageClass, LinkageSpec::C, 0, result, 0 );
405 tmp->get_type()->set_isConst( false );
406
407 // create and resolve copy constructor
408 CP_CTOR_PRINT( std::cerr << "makeCtorDtor for an argument" << std::endl; )
409 ApplicationExpr * cpCtor = makeCtorDtor( "?{}", tmp, arg );
410
411 // if the chosen constructor is intrinsic, the copy is unnecessary, so
412 // don't create the temporary and don't call the copy constructor
413 VariableExpr * function = dynamic_cast< VariableExpr * >( cpCtor->get_function() );
414 assert( function );
415 if ( function->get_var()->get_linkage() != LinkageSpec::Intrinsic ) {
416 // replace argument to function call with temporary
417 arg = new CommaExpr( cpCtor, new VariableExpr( tmp ) );
418 impCpCtorExpr->get_tempDecls().push_back( tmp );
419 impCpCtorExpr->get_dtors().push_front( makeCtorDtor( "^?{}", tmp ) );
420 } // if
421 }
[c2931ea]422
[1132b62]423 void ResolveCopyCtors::destructRet( Expression * ret, ImplicitCopyCtorExpr * impCpCtorExpr ) {
424 if ( TupleType * tupleType = dynamic_cast< TupleType * > ( ret->get_result() ) ) {
425 int idx = 0;
426 for ( Type *& t : tupleType->get_types() ) {
427 (void)t;
428 destructRet( new TupleIndexExpr( ret->clone(), idx++ ), impCpCtorExpr );
429 }
430 return;
431 }
432 impCpCtorExpr->get_dtors().push_front( makeCtorDtor( "^?{}", new AddressExpr( ret ) ) );
433 }
434
435 void ResolveCopyCtors::visit( ImplicitCopyCtorExpr *impCpCtorExpr ) {
[c2931ea]436 CP_CTOR_PRINT( std::cerr << "ResolveCopyCtors: " << impCpCtorExpr << std::endl; )
437 Visitor::visit( impCpCtorExpr );
438 env = impCpCtorExpr->get_env(); // xxx - maybe we really should just have a PolyIndexer...
439
440 ApplicationExpr * appExpr = impCpCtorExpr->get_callExpr();
441
442 // take each argument and attempt to copy construct it.
443 for ( Expression * & arg : appExpr->get_args() ) {
[1132b62]444 copyConstructArg( arg, impCpCtorExpr );
[adcc065]445 } // for
[db4ecc5]446
[adcc065]447 // each return value from the call needs to be connected with an ObjectDecl at the call site, which is
448 // initialized with the return value and is destructed later
[c2931ea]449 // xxx - handle multiple return values
450 ApplicationExpr * callExpr = impCpCtorExpr->get_callExpr();
[adcc065]451 // xxx - is this right? callExpr may not have the right environment, because it was attached at a higher
452 // level. Trying to pass that environment along.
[c2931ea]453 callExpr->set_env( impCpCtorExpr->get_env()->clone() );
[906e24d]454 Type * result = appExpr->get_result();
455 if ( ! result->isVoid() ) {
[1132b62]456 static UniqueName retNamer("_tmp_cp_ret");
[c2931ea]457 result = result->clone();
458 impCpCtorExpr->get_env()->apply( result );
459 ObjectDecl * ret = new ObjectDecl( retNamer.newName(), DeclarationNode::NoStorageClass, LinkageSpec::C, 0, result, 0 );
460 ret->get_type()->set_isConst( false );
461 impCpCtorExpr->get_returnDecls().push_back( ret );
462 CP_CTOR_PRINT( std::cerr << "makeCtorDtor for a return" << std::endl; )
[1132b62]463 destructRet( new VariableExpr( ret ) , impCpCtorExpr );
[adcc065]464 } // for
[c2931ea]465 CP_CTOR_PRINT( std::cerr << "after Resolving: " << impCpCtorExpr << std::endl; )
[db4ecc5]466 }
467
468
[c2931ea]469 Expression * FixCopyCtors::mutate( ImplicitCopyCtorExpr * impCpCtorExpr ) {
470 CP_CTOR_PRINT( std::cerr << "FixCopyCtors: " << impCpCtorExpr << std::endl; )
471
472 impCpCtorExpr = dynamic_cast< ImplicitCopyCtorExpr * >( Mutator::mutate( impCpCtorExpr ) );
473 assert( impCpCtorExpr );
[db4ecc5]474
[c2931ea]475 std::list< ObjectDecl * > & tempDecls = impCpCtorExpr->get_tempDecls();
476 std::list< ObjectDecl * > & returnDecls = impCpCtorExpr->get_returnDecls();
477 std::list< Expression * > & dtors = impCpCtorExpr->get_dtors();
[845cedc]478
[c2931ea]479 // add all temporary declarations and their constructors
480 for ( ObjectDecl * obj : tempDecls ) {
481 stmtsToAdd.push_back( new DeclStmt( noLabels, obj ) );
[adcc065]482 } // for
[c2931ea]483 for ( ObjectDecl * obj : returnDecls ) {
484 stmtsToAdd.push_back( new DeclStmt( noLabels, obj ) );
[adcc065]485 } // for
[db4ecc5]486
[c2931ea]487 // add destructors after current statement
488 for ( Expression * dtor : dtors ) {
489 stmtsToAddAfter.push_back( new ExprStmt( noLabels, dtor ) );
[adcc065]490 } // for
[db4ecc5]491
[c2931ea]492 // xxx - update to work with multiple return values
493 ObjectDecl * returnDecl = returnDecls.empty() ? NULL : returnDecls.front();
494 Expression * callExpr = impCpCtorExpr->get_callExpr();
495
496 CP_CTOR_PRINT( std::cerr << "Coming out the back..." << impCpCtorExpr << std::endl; )
497
498 // detach fields from wrapper node so that it can be deleted without deleting too much
499 dtors.clear();
500 tempDecls.clear();
501 returnDecls.clear();
502 impCpCtorExpr->set_callExpr( NULL );
503 impCpCtorExpr->set_env( NULL );
504 delete impCpCtorExpr;
505
506 if ( returnDecl ) {
507 UntypedExpr * assign = new UntypedExpr( new NameExpr( "?=?" ) );
508 assign->get_args().push_back( new VariableExpr( returnDecl ) );
509 assign->get_args().push_back( callExpr );
510 // know the result type of the assignment is the type of the LHS (minus the pointer), so
511 // add that onto the assignment expression so that later steps have the necessary information
[906e24d]512 assign->set_result( returnDecl->get_type()->clone() );
[c2931ea]513
514 Expression * retExpr = new CommaExpr( assign, new VariableExpr( returnDecl ) );
[906e24d]515 if ( callExpr->get_result()->get_isLvalue() ) {
[adcc065]516 // lvalue returning functions are funny. Lvalue.cc inserts a *? in front of any lvalue returning
517 // non-intrinsic function. Add an AddressExpr to the call to negate the derefence and change the
518 // type of the return temporary from T to T* to properly capture the return value. Then dereference
519 // the result of the comma expression, since the lvalue returning call was originally wrapped with
520 // an AddressExpr. Effectively, this turns
[c2931ea]521 // lvalue T f();
522 // &*f()
523 // into
524 // T * tmp_cp_retN;
525 // tmp_cp_ret_N = &*(tmp_cp_ret_N = &*f(), tmp_cp_ret);
526 // which work out in terms of types, but is pretty messy. It would be nice to find a better way.
527 assign->get_args().back() = new AddressExpr( assign->get_args().back() );
528
529 Type * resultType = returnDecl->get_type()->clone();
530 returnDecl->set_type( new PointerType( Type::Qualifiers(), returnDecl->get_type() ) );
531 UntypedExpr * deref = new UntypedExpr( new NameExpr( "*?" ) );
532 deref->get_args().push_back( retExpr );
[906e24d]533 deref->set_result( resultType );
[c2931ea]534 retExpr = deref;
[adcc065]535 } // if
[b6fe7e6]536 retExpr->set_env( env->clone() );
[c2931ea]537 return retExpr;
538 } else {
539 return callExpr;
[adcc065]540 } // if
[4ffdd63]541 }
[c2931ea]542
543 DeclarationWithType *FixInit::mutate( ObjectDecl *objDecl ) {
[adcc065]544 // first recursively handle pieces of ObjectDecl so that they aren't missed by other visitors when the init
545 // is removed from the ObjectDecl
[c2931ea]546 objDecl = dynamic_cast< ObjectDecl * >( Mutator::mutate( objDecl ) );
547
548 if ( ConstructorInit * ctorInit = dynamic_cast< ConstructorInit * >( objDecl->get_init() ) ) {
549 // a decision should have been made by the resolver, so ctor and init are not both non-NULL
550 assert( ! ctorInit->get_ctor() || ! ctorInit->get_init() );
551 if ( Statement * ctor = ctorInit->get_ctor() ) {
552 if ( objDecl->get_storageClass() == DeclarationNode::Static ) {
[72e9222]553 // originally wanted to take advantage of gcc nested functions, but
[f9cebb5]554 // we get memory errors with this approach. To remedy this, the static
555 // variable is hoisted when the destructor needs to be called.
[72e9222]556 //
[c2931ea]557 // generate:
[f9cebb5]558 // static T __objName_static_varN;
[72e9222]559 // void __objName_dtor_atexitN() {
[f9cebb5]560 // __dtor__...;
[72e9222]561 // }
562 // int f(...) {
563 // ...
564 // static bool __objName_uninitialized = true;
565 // if (__objName_uninitialized) {
566 // __ctor(__objName);
567 // __objName_uninitialized = false;
[f9cebb5]568 // atexit(__objName_dtor_atexitN);
[c2931ea]569 // }
[72e9222]570 // ...
[c2931ea]571 // }
572
[72e9222]573 static UniqueName dtorCallerNamer( "_dtor_atexit" );
574
575 // static bool __objName_uninitialized = true
[c2931ea]576 BasicType * boolType = new BasicType( Type::Qualifiers(), BasicType::Bool );
577 SingleInit * boolInitExpr = new SingleInit( new ConstantExpr( Constant( boolType->clone(), "1" ) ), noDesignators );
578 ObjectDecl * isUninitializedVar = new ObjectDecl( objDecl->get_mangleName() + "_uninitialized", DeclarationNode::Static, LinkageSpec::Cforall, 0, boolType, boolInitExpr );
579 isUninitializedVar->fixUniqueId();
580
581 // __objName_uninitialized = false;
582 UntypedExpr * setTrue = new UntypedExpr( new NameExpr( "?=?" ) );
583 setTrue->get_args().push_back( new VariableExpr( isUninitializedVar ) );
584 setTrue->get_args().push_back( new ConstantExpr( Constant( boolType->clone(), "0" ) ) );
585
586 // generate body of if
587 CompoundStmt * initStmts = new CompoundStmt( noLabels );
588 std::list< Statement * > & body = initStmts->get_kids();
589 body.push_back( ctor );
590 body.push_back( new ExprStmt( noLabels, setTrue ) );
591
592 // put it all together
593 IfStmt * ifStmt = new IfStmt( noLabels, new VariableExpr( isUninitializedVar ), initStmts, 0 );
594 stmtsToAddAfter.push_back( new DeclStmt( noLabels, isUninitializedVar ) );
595 stmtsToAddAfter.push_back( ifStmt );
[72e9222]596
[f9cebb5]597 if ( ctorInit->get_dtor() ) {
598 // if the object has a non-trivial destructor, have to
599 // hoist it and the object into the global space and
600 // call the destructor function with atexit.
601
602 Statement * dtorStmt = ctorInit->get_dtor()->clone();
603
604 // void __objName_dtor_atexitN(...) {...}
605 FunctionDecl * dtorCaller = new FunctionDecl( objDecl->get_mangleName() + dtorCallerNamer.newName(), DeclarationNode::Static, LinkageSpec::C, new FunctionType( Type::Qualifiers(), false ), new CompoundStmt( noLabels ), false, false );
606 dtorCaller->fixUniqueId();
[c8dfcd3]607 dtorCaller->get_statements()->push_back( dtorStmt );
[f9cebb5]608
609 // atexit(dtor_atexit);
610 UntypedExpr * callAtexit = new UntypedExpr( new NameExpr( "atexit" ) );
611 callAtexit->get_args().push_back( new VariableExpr( dtorCaller ) );
612
613 body.push_back( new ExprStmt( noLabels, callAtexit ) );
614
615 // hoist variable and dtor caller decls to list of decls that will be added into global scope
616 staticDtorDecls.push_back( objDecl );
617 staticDtorDecls.push_back( dtorCaller );
618
619 // need to rename object uniquely since it now appears
620 // at global scope and there could be multiple function-scoped
621 // static variables with the same name in different functions.
[c8dfcd3]622 // Note: it isn't sufficient to modify only the mangleName, because
623 // then subsequent Indexer passes can choke on seeing the object's name
624 // if another object has the same name and type. An unfortunate side-effect
625 // of renaming the object is that subsequent NameExprs may fail to resolve,
626 // but there shouldn't be any remaining past this point.
[f9cebb5]627 static UniqueName staticNamer( "_static_var" );
[c8dfcd3]628 objDecl->set_name( objDecl->get_name() + staticNamer.newName() );
629 objDecl->set_mangleName( SymTab::Mangler::mangle( objDecl ) );
[f9cebb5]630
631 objDecl->set_init( NULL );
632 ctorInit->set_ctor( NULL );
633 delete ctorInit;
634
635 // xxx - temporary hack: need to return a declaration, but want to hoist the current object out of this scope
636 // create a new object which is never used
637 static UniqueName dummyNamer( "_dummy" );
638 ObjectDecl * dummy = new ObjectDecl( dummyNamer.newName(), DeclarationNode::Static, LinkageSpec::Cforall, 0, new PointerType( Type::Qualifiers(), new VoidType( Type::Qualifiers() ) ), 0, std::list< Attribute * >{ new Attribute("unused") } );
639 return dummy;
640 }
[c2931ea]641 } else {
642 stmtsToAddAfter.push_back( ctor );
[adcc065]643 } // if
[c2931ea]644 objDecl->set_init( NULL );
645 ctorInit->set_ctor( NULL );
646 } else if ( Initializer * init = ctorInit->get_init() ) {
647 objDecl->set_init( init );
648 ctorInit->set_init( NULL );
649 } else {
650 // no constructor and no initializer, which is okay
651 objDecl->set_init( NULL );
[adcc065]652 } // if
[c2931ea]653 delete ctorInit;
[adcc065]654 } // if
[c2931ea]655 return objDecl;
[db4ecc5]656 }
657
[c2931ea]658 void ObjDeclCollector::visit( CompoundStmt *compoundStmt ) {
659 std::set< ObjectDecl * > prevVars = curVars;
660 Parent::visit( compoundStmt );
661 curVars = prevVars;
[db4ecc5]662 }
663
[c2931ea]664 void ObjDeclCollector::visit( DeclStmt *stmt ) {
[4b2589a]665 // keep track of all variables currently in scope
[c2931ea]666 if ( ObjectDecl * objDecl = dynamic_cast< ObjectDecl * > ( stmt->get_decl() ) ) {
667 curVars.insert( objDecl );
[adcc065]668 } // if
[e39aa0f]669 Parent::visit( stmt );
[db4ecc5]670 }
671
[c2931ea]672 void LabelFinder::handleStmt( Statement * stmt ) {
[4b2589a]673 // for each label, remember the variables in scope at that label.
[c2931ea]674 for ( Label l : stmt->get_labels() ) {
675 vars[l] = curVars;
[adcc065]676 } // for
[71f4e4f]677 }
[f1e012b]678
[ec79847]679 template<typename Iterator, typename OutputIterator>
680 void insertDtors( Iterator begin, Iterator end, OutputIterator out ) {
681 for ( Iterator it = begin ; it != end ; ++it ) {
[adcc065]682 // extract destructor statement from the object decl and insert it into the output. Note that this is
683 // only called on lists of non-static objects with implicit non-intrinsic dtors, so if the user manually
684 // calls an intrinsic dtor then the call must (and will) still be generated since the argument may
685 // contain side effects.
[c2931ea]686 ObjectDecl * objDecl = *it;
687 ConstructorInit * ctorInit = dynamic_cast< ConstructorInit * >( objDecl->get_init() );
688 assert( ctorInit && ctorInit->get_dtor() );
689 *out++ = ctorInit->get_dtor()->clone();
[adcc065]690 } // for
[f1e012b]691 }
[39786813]692
[c2931ea]693 void InsertDtors::visit( ObjectDecl * objDecl ) {
694 // remember non-static destructed objects so that their destructors can be inserted later
695 if ( objDecl->get_storageClass() != DeclarationNode::Static ) {
696 if ( ConstructorInit * ctorInit = dynamic_cast< ConstructorInit * >( objDecl->get_init() ) ) {
697 // a decision should have been made by the resolver, so ctor and init are not both non-NULL
698 assert( ! ctorInit->get_ctor() || ! ctorInit->get_init() );
699 Statement * dtor = ctorInit->get_dtor();
[f9cebb5]700 if ( dtor && ! isIntrinsicSingleArgCallStmt( dtor ) ) {
[c2931ea]701 // don't need to call intrinsic dtor, because it does nothing, but
702 // non-intrinsic dtors must be called
703 reverseDeclOrder.front().push_front( objDecl );
[adcc065]704 } // if
705 } // if
706 } // if
[c2931ea]707 Parent::visit( objDecl );
708 }
[39786813]709
[c2931ea]710 void InsertDtors::visit( CompoundStmt * compoundStmt ) {
[adcc065]711 // visit statements - this will also populate reverseDeclOrder list. don't want to dump all destructors
712 // when block is left, just the destructors associated with variables defined in this block, so push a new
713 // list to the top of the stack so that we can differentiate scopes
[c2931ea]714 reverseDeclOrder.push_front( OrderedDecls() );
715 Parent::visit( compoundStmt );
[39786813]716
[4b2589a]717 // add destructors for the current scope that we're exiting
[c2931ea]718 std::list< Statement * > & statements = compoundStmt->get_kids();
719 insertDtors( reverseDeclOrder.front().begin(), reverseDeclOrder.front().end(), back_inserter( statements ) );
720 reverseDeclOrder.pop_front();
[39786813]721 }
722
[c2931ea]723 void InsertDtors::visit( ReturnStmt * returnStmt ) {
[4b2589a]724 // return exits all scopes, so dump destructors for all scopes
[c2931ea]725 for ( OrderedDecls & od : reverseDeclOrder ) {
726 insertDtors( od.begin(), od.end(), back_inserter( stmtsToAdd ) );
[adcc065]727 } // for
[39786813]728 }
[f1e012b]729
[adcc065]730 // Handle break/continue/goto in the same manner as C++. Basic idea: any objects that are in scope at the
731 // BranchStmt but not at the labelled (target) statement must be destructed. If there are any objects in scope
732 // at the target location but not at the BranchStmt then those objects would be uninitialized so notify the user
733 // of the error. See C++ Reference 6.6 Jump Statements for details.
[c2931ea]734 void InsertDtors::handleGoto( BranchStmt * stmt ) {
[e39aa0f]735 assert( stmt->get_target() != "" && "BranchStmt missing a label" );
[c2931ea]736 // S_L = lvars = set of objects in scope at label definition
737 // S_G = curVars = set of objects in scope at goto statement
738 ObjectSet & lvars = labelVars[ stmt->get_target() ];
739
740 DTOR_PRINT(
741 std::cerr << "at goto label: " << stmt->get_target().get_name() << std::endl;
742 std::cerr << "S_G = " << printSet( curVars ) << std::endl;
743 std::cerr << "S_L = " << printSet( lvars ) << std::endl;
744 )
745
746 ObjectSet diff;
747 // S_L-S_G results in set of objects whose construction is skipped - it's an error if this set is non-empty
748 std::set_difference( lvars.begin(), lvars.end(), curVars.begin(), curVars.end(), std::inserter( diff, diff.begin() ) );
749 DTOR_PRINT(
750 std::cerr << "S_L-S_G = " << printSet( diff ) << std::endl;
751 )
752 if ( ! diff.empty() ) {
753 throw SemanticError( std::string("jump to label '") + stmt->get_target().get_name() + "' crosses initialization of " + (*diff.begin())->get_name() + " ", stmt );
[adcc065]754 } // if
[c2931ea]755 // S_G-S_L results in set of objects that must be destructed
756 diff.clear();
757 std::set_difference( curVars.begin(), curVars.end(), lvars.begin(), lvars.end(), std::inserter( diff, diff.end() ) );
758 DTOR_PRINT(
759 std::cerr << "S_G-S_L = " << printSet( diff ) << std::endl;
760 )
761 if ( ! diff.empty() ) {
762 // go through decl ordered list of objectdecl. for each element that occurs in diff, output destructor
763 OrderedDecls ordered;
764 for ( OrderedDecls & rdo : reverseDeclOrder ) {
765 // add elements from reverseDeclOrder into ordered if they occur in diff - it is key that this happens in reverse declaration order.
766 copy_if( rdo.begin(), rdo.end(), back_inserter( ordered ), [&]( ObjectDecl * objDecl ) { return diff.count( objDecl ); } );
[adcc065]767 } // for
[c2931ea]768 insertDtors( ordered.begin(), ordered.end(), back_inserter( stmtsToAdd ) );
[adcc065]769 } // if
[c2931ea]770 }
[39786813]771
[c2931ea]772 void InsertDtors::visit( BranchStmt * stmt ) {
773 switch( stmt->get_type() ) {
[adcc065]774 case BranchStmt::Continue:
775 case BranchStmt::Break:
776 // could optimize the break/continue case, because the S_L-S_G check is unnecessary (this set should
777 // always be empty), but it serves as a small sanity check.
778 case BranchStmt::Goto:
779 handleGoto( stmt );
780 break;
781 default:
782 assert( false );
783 } // switch
[c2931ea]784 }
[79970ed]785
786 bool checkWarnings( FunctionDecl * funcDecl ) {
787 // only check for warnings if the current function is a user-defined
788 // constructor or destructor
789 if ( ! funcDecl ) return false;
790 if ( ! funcDecl->get_statements() ) return false;
791 return isCtorDtor( funcDecl->get_name() ) && ! LinkageSpec::isOverridable( funcDecl->get_linkage() );
792 }
793
[c8dfcd3]794 void GenStructMemberCalls::visit( FunctionDecl * funcDecl ) {
795 ValueGuard< FunctionDecl * > oldFunction( funcDecl );
796 ValueGuard< std::set< DeclarationWithType * > > oldUnhandled( unhandled );
797 ValueGuard< std::set< DeclarationWithType * > > oldUsedUninit( usedUninit );
798 ValueGuard< ObjectDecl * > oldThisParam( thisParam );
799 ValueGuard< bool > oldIsCtor( isCtor );
[44f6341]800 ValueGuard< StructDecl * > oldStructDecl( structDecl );
[c8dfcd3]801
802 // need to start with fresh sets
803 unhandled.clear();
804 usedUninit.clear();
[79970ed]805
806 function = funcDecl;
[c8dfcd3]807 isCtor = isConstructor( function->get_name() );
808 if ( checkWarnings( function ) ) {
809 FunctionType * type = function->get_functionType();
[79970ed]810 assert( ! type->get_parameters().empty() );
811 thisParam = safe_dynamic_cast< ObjectDecl * >( type->get_parameters().front() );
812 PointerType * ptrType = safe_dynamic_cast< PointerType * > ( thisParam->get_type() );
813 StructInstType * structType = dynamic_cast< StructInstType * >( ptrType->get_base() );
814 if ( structType ) {
[44f6341]815 structDecl = structType->get_baseStruct();
[79970ed]816 for ( Declaration * member : structDecl->get_members() ) {
817 if ( ObjectDecl * field = dynamic_cast< ObjectDecl * >( member ) ) {
818 // record all of the struct type's members that need to be constructed or
819 // destructed by the end of the function
820 unhandled.insert( field );
821 }
822 }
823 }
824 }
[c8dfcd3]825 Parent::visit( function );
826
827 // remove the unhandled objects from usedUninit, because a call is inserted
828 // to handle them - only objects that are later constructed are used uninitialized.
829 std::set< DeclarationWithType * > diff;
830 std::set_difference( usedUninit.begin(), usedUninit.end(), unhandled.begin(), unhandled.end(), std::inserter( diff, diff.begin() ) );
831 for ( DeclarationWithType * member : diff ) {
[44f6341]832 emit( "in ", CodeGen::genType( function->get_functionType(), function->get_name(), false ), ", field ", member->get_name(), " used before being constructed" );
[79970ed]833 }
834
[c8dfcd3]835 if ( ! unhandled.empty() ) {
836 // need to explicitly re-add function parameters in order to resolve copy constructors
837 enterScope();
[b16898e]838 maybeAccept( function->get_functionType(), *this );
[44f6341]839
840 // need to iterate through members in reverse in order for
841 // ctor/dtor statements to come out in the right order
[1ba88a0]842 for ( Declaration * member : reverseIterate( structDecl->get_members() ) ) {
[44f6341]843 DeclarationWithType * field = dynamic_cast< DeclarationWithType * >( member );
844 // skip non-DWT members
845 if ( ! field ) continue;
846 // skip handled members
847 if ( ! unhandled.count( field ) ) continue;
848
849 // insert and resolve default/copy constructor call for each field that's unhandled
[c8dfcd3]850 std::list< Statement * > stmt;
851 UntypedExpr * deref = new UntypedExpr( new NameExpr( "*?" ) );
852 deref->get_args().push_back( new VariableExpr( thisParam ) );
[4d4882a]853
854 Expression * arg2 = 0;
855 if ( isCopyConstructor( function ) ) {
[44f6341]856 // if copy ctor, need to pass second-param-of-this-function.field
[4d4882a]857 std::list< DeclarationWithType * > & params = function->get_functionType()->get_parameters();
858 assert( params.size() == 2 );
[44f6341]859 arg2 = new MemberExpr( field, new VariableExpr( params.back() ) );
[4d4882a]860 }
861 InitExpander srcParam( arg2 );
[44f6341]862 SymTab::genImplicitCall( srcParam, new MemberExpr( field, deref ), function->get_name(), back_inserter( stmt ), field, isCtor );
[c8dfcd3]863
864 assert( stmt.size() <= 1 );
865 if ( stmt.size() == 1 ) {
866 Statement * callStmt = stmt.front();
867
868 MutatingResolver resolver( *this );
869 try {
870 callStmt->acceptMutator( resolver );
871 if ( isCtor ) {
872 function->get_statements()->push_front( callStmt );
873 } else {
874 // destructor statements should be added at the end
875 function->get_statements()->push_back( callStmt );
876 }
877 } catch ( SemanticError & error ) {
[44f6341]878 emit( "in ", CodeGen::genType( function->get_functionType(), function->get_name(), false ), ", field ", field->get_name(), " not explicitly ", isCtor ? "constructed" : "destructed", " and no ", isCtor ? "default constructor" : "destructor", " found" );
[c8dfcd3]879 }
880 }
881 }
882 leaveScope();
883 }
[79970ed]884 }
885
[c8dfcd3]886 void GenStructMemberCalls::visit( ApplicationExpr * appExpr ) {
[79970ed]887 if ( ! checkWarnings( function ) ) return;
888
889 std::string fname = getFunctionName( appExpr );
890 if ( fname == function->get_name() ) {
891 // call to same kind of function
892 Expression * firstParam = appExpr->get_args().front();
893
894 if ( VariableExpr * varExpr = dynamic_cast< VariableExpr * >( firstParam ) ) {
895 // if calling another constructor on thisParam, assume that function handles
896 // all members - if it doesn't a warning will appear in that function.
897 if ( varExpr->get_var() == thisParam ) {
898 unhandled.clear();
899 }
900 } else {
901 // if first parameter is a member expression then
902 // remove the member from unhandled set.
903 handleFirstParam( firstParam );
904 }
905 }
906
907 Parent::visit( appExpr );
908 }
909
[c8dfcd3]910 void GenStructMemberCalls::handleFirstParam( Expression * firstParam ) {
[79970ed]911 using namespace std;
912 if ( AddressExpr * addrExpr = dynamic_cast< AddressExpr * >( firstParam ) ) {
913 if ( MemberExpr * memberExpr = dynamic_cast< MemberExpr * >( addrExpr->get_arg() ) ) {
914 if ( ApplicationExpr * deref = dynamic_cast< ApplicationExpr * >( memberExpr->get_aggregate() ) ) {
915 if ( getFunctionName( deref ) == "*?" && deref->get_args().size() == 1 ) {
916 if ( VariableExpr * varExpr = dynamic_cast< VariableExpr * >( deref->get_args().front() ) ) {
917 if ( varExpr->get_var() == thisParam ) {
918 unhandled.erase( memberExpr->get_member() );
919 }
920 }
921 }
922 }
923 }
924 }
925 }
926
[c8dfcd3]927 void GenStructMemberCalls::visit( MemberExpr * memberExpr ) {
[79970ed]928 if ( ! checkWarnings( function ) ) return;
[c8dfcd3]929 if ( ! isCtor ) return;
[79970ed]930
931 if ( ApplicationExpr * deref = dynamic_cast< ApplicationExpr * >( memberExpr->get_aggregate() ) ) {
932 if ( getFunctionName( deref ) == "*?" && deref->get_args().size() == 1 ) {
933 if ( VariableExpr * varExpr = dynamic_cast< VariableExpr * >( deref->get_args().front() ) ) {
934 if ( varExpr->get_var() == thisParam ) {
935 if ( unhandled.count( memberExpr->get_member() ) ) {
936 // emit a warning because a member was used before it was constructed
[c8dfcd3]937 usedUninit.insert( memberExpr->get_member() );
[79970ed]938 }
939 }
940 }
941 }
942 }
943 Parent::visit( memberExpr );
944 }
[3906301]945
946 template< typename Visitor, typename... Params >
947 void error( Visitor & v, const Params &... params ) {
948 v.errors.append( toString( params... ) );
949 }
950
951 template< typename... Params >
[c8dfcd3]952 void GenStructMemberCalls::emit( const Params &... params ) {
[3906301]953 // toggle warnings vs. errors here.
954 // warn( params... );
955 error( *this, params... );
956 }
[c8dfcd3]957
958 DeclarationWithType * MutatingResolver::mutate( ObjectDecl *objectDecl ) {
959 // add object to the indexer assumes that there will be no name collisions
960 // in generated code. If this changes, add mutate methods for entities with
961 // scope and call {enter,leave}Scope explicitly.
962 objectDecl->accept( indexer );
963 return objectDecl;
964 }
965
966 Expression* MutatingResolver::mutate( UntypedExpr *untypedExpr ) {
967 return safe_dynamic_cast< ApplicationExpr * >( ResolvExpr::findVoidExpression( untypedExpr, indexer ) );
968 }
[b6fe7e6]969
970 Expression * FixCtorExprs::mutate( ConstructorExpr * ctorExpr ) {
971 static UniqueName tempNamer( "_tmp_ctor_expr" );
[906e24d]972 assert( ctorExpr->has_result() && ctorExpr->get_result()->size() == 1 );
973 ObjectDecl * tmp = new ObjectDecl( tempNamer.newName(), DeclarationNode::NoStorageClass, LinkageSpec::C, nullptr, ctorExpr->get_result()->clone(), nullptr );
[b6fe7e6]974 addDeclaration( tmp );
975
976 ApplicationExpr * callExpr = safe_dynamic_cast< ApplicationExpr * > ( ctorExpr->get_callExpr() );
977 TypeSubstitution * env = ctorExpr->get_env();
978 ctorExpr->set_callExpr( nullptr );
979 ctorExpr->set_env( nullptr );
980
981 Expression *& firstArg = callExpr->get_args().front();
982 UntypedExpr * assign = new UntypedExpr( new NameExpr( "?=?" ) );
983 assign->get_args().push_back( new VariableExpr( tmp ) );
984 assign->get_args().push_back( firstArg );
[906e24d]985 assign->set_result( ctorExpr->get_result()->clone() );
[b6fe7e6]986 firstArg = assign;
987
988 CommaExpr * commaExpr = new CommaExpr( callExpr, new VariableExpr( tmp ) );
989 commaExpr->set_env( env );
990 delete ctorExpr;
991 return commaExpr;
992 }
[c2931ea]993 } // namespace
[71f4e4f]994} // namespace InitTweak
995
996// Local Variables: //
997// tab-width: 4 //
998// mode: c++ //
999// compile-command: "make install" //
1000// End: //
Note: See TracBrowser for help on using the repository browser.