source: src/InitTweak/FixInit.cc@ cf90b88

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 cf90b88 was dc2334c, checked in by Rob Schluntz <rschlunt@…>, 9 years ago

Convert FixCopyCtors to PassVisitor

  • Property mode set to 100644
File size: 51.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// FixInit.h --
8//
9// Author : Rob Schluntz
10// Created On : Wed Jan 13 16:29:30 2016
11// Last Modified By : Peter A. Buhr
12// Last Modified On : Wed Jun 21 17:35:05 2017
13// Update Count : 74
14//
15#include "FixInit.h"
16
17#include <stddef.h> // for NULL
18#include <algorithm> // for set_difference, copy_if
19#include <cassert> // for assert, strict_dynamic_cast
20#include <iostream> // for operator<<, ostream, basic_ost...
21#include <iterator> // for insert_iterator, back_inserter
22#include <list> // for _List_iterator, list, list<>::...
23#include <map> // for _Rb_tree_iterator, _Rb_tree_co...
24#include <memory> // for allocator_traits<>::value_type
25#include <set> // for set, set<>::value_type
26#include <unordered_map> // for unordered_map, unordered_map<>...
27#include <unordered_set> // for unordered_set
28#include <utility> // for pair
29
30#include "CodeGen/GenType.h" // for genPrettyType
31#include "CodeGen/OperatorTable.h"
32#include "Common/PassVisitor.h" // for PassVisitor, WithStmtsToAdd
33#include "Common/SemanticError.h" // for SemanticError
34#include "Common/UniqueName.h" // for UniqueName
35#include "Common/utility.h" // for CodeLocation, ValueGuard, toSt...
36#include "FixGlobalInit.h" // for fixGlobalInit
37#include "GenInit.h" // for genCtorDtor
38#include "GenPoly/GenPoly.h" // for getFunctionType
39#include "GenPoly/PolyMutator.h" // for PolyMutator
40#include "InitTweak.h" // for getFunctionName, getCallArg
41#include "Parser/LinkageSpec.h" // for C, Spec, Cforall, isBuiltin
42#include "ResolvExpr/Resolver.h" // for findVoidExpression
43#include "ResolvExpr/typeops.h" // for typesCompatible
44#include "SymTab/Autogen.h" // for genImplicitCall
45#include "SymTab/Indexer.h" // for Indexer
46#include "SymTab/Mangler.h" // for Mangler
47#include "SynTree/AddStmtVisitor.h" // for AddStmtVisitor
48#include "SynTree/Attribute.h" // for Attribute
49#include "SynTree/Constant.h" // for Constant
50#include "SynTree/Declaration.h" // for ObjectDecl, FunctionDecl, Decl...
51#include "SynTree/Expression.h" // for UniqueExpr, VariableExpr, Unty...
52#include "SynTree/Initializer.h" // for ConstructorInit, SingleInit
53#include "SynTree/Label.h" // for Label, noLabels, operator<
54#include "SynTree/Mutator.h" // for mutateAll, Mutator, maybeMutate
55#include "SynTree/Statement.h" // for ExprStmt, CompoundStmt, Branch...
56#include "SynTree/Type.h" // for Type, Type::StorageClasses
57#include "SynTree/TypeSubstitution.h" // for TypeSubstitution, operator<<
58#include "SynTree/Visitor.h" // for acceptAll, maybeAccept
59
60bool ctordtorp = false; // print all debug
61bool ctorp = false; // print ctor debug
62bool cpctorp = false; // print copy ctor debug
63bool dtorp = false; // print dtor debug
64#define PRINT( text ) if ( ctordtorp ) { text }
65#define CP_CTOR_PRINT( text ) if ( ctordtorp || cpctorp ) { text }
66#define DTOR_PRINT( text ) if ( ctordtorp || dtorp ) { text }
67
68namespace InitTweak {
69 namespace {
70 typedef std::unordered_map< int, int > UnqCount;
71
72 struct InsertImplicitCalls : public WithTypeSubstitution {
73 /// wrap function application expressions as ImplicitCopyCtorExpr nodes so that it is easy to identify which
74 /// function calls need their parameters to be copy constructed
75 static void insert( std::list< Declaration * > & translationUnit );
76
77 Expression * postmutate( ApplicationExpr * appExpr );
78 };
79
80 struct ResolveCopyCtors final : public WithIndexer, public WithShortCircuiting, public WithTypeSubstitution {
81 /// generate temporary ObjectDecls for each argument and return value of each ImplicitCopyCtorExpr,
82 /// generate/resolve copy construction expressions for each, and generate/resolve destructors for both
83 /// arguments and return value temporaries
84 static void resolveImplicitCalls( std::list< Declaration * > & translationUnit, UnqCount & unqCount );
85
86 ResolveCopyCtors( UnqCount & unqCount ) : unqCount( unqCount ) {}
87
88 void postvisit( ImplicitCopyCtorExpr * impCpCtorExpr );
89 void postvisit( StmtExpr * stmtExpr );
90 void previsit( UniqueExpr * unqExpr );
91 void postvisit( UniqueExpr * unqExpr );
92
93 /// create and resolve ctor/dtor expression: fname(var, [cpArg])
94 Expression * makeCtorDtor( const std::string & fname, ObjectDecl * var, Expression * cpArg = NULL );
95 /// true if type does not need to be copy constructed to ensure correctness
96 bool skipCopyConstruct( Type * type );
97 void copyConstructArg( Expression *& arg, ImplicitCopyCtorExpr * impCpCtorExpr );
98 void destructRet( ObjectDecl * ret, ImplicitCopyCtorExpr * impCpCtorExpr );
99
100 UnqCount & unqCount; // count the number of times each unique expr ID appears
101 std::unordered_set< int > vars;
102 };
103
104 /// collects constructed object decls - used as a base class
105 struct ObjDeclCollector : public WithGuards, public WithShortCircuiting {
106 // use ordered data structure to maintain ordering for set_difference and for consistent error messages
107 typedef std::list< ObjectDecl * > ObjectSet;
108 void previsit( CompoundStmt *compoundStmt );
109 void previsit( DeclStmt *stmt );
110
111 // don't go into other functions
112 void previsit( FunctionDecl * ) { visit_children = false; }
113
114 protected:
115 ObjectSet curVars;
116 };
117
118 // debug
119 template<typename ObjectSet>
120 struct PrintSet {
121 PrintSet( const ObjectSet & objs ) : objs( objs ) {}
122 const ObjectSet & objs;
123 };
124 template<typename ObjectSet>
125 PrintSet<ObjectSet> printSet( const ObjectSet & objs ) { return PrintSet<ObjectSet>( objs ); }
126 template<typename ObjectSet>
127 std::ostream & operator<<( std::ostream & out, const PrintSet<ObjectSet> & set) {
128 out << "{ ";
129 for ( ObjectDecl * obj : set.objs ) {
130 out << obj->get_name() << ", " ;
131 } // for
132 out << " }";
133 return out;
134 }
135
136 struct LabelFinder final : public ObjDeclCollector {
137 typedef std::map< Label, ObjectSet > LabelMap;
138 // map of Label -> live variables at that label
139 LabelMap vars;
140
141 typedef ObjDeclCollector Parent;
142 using Parent::previsit;
143 void previsit( Statement * stmt );
144
145 void previsit( CompoundStmt *compoundStmt );
146 void previsit( DeclStmt *stmt );
147 };
148
149 struct InsertDtors final : public ObjDeclCollector, public WithStmtsToAdd {
150 /// insert destructor calls at the appropriate places. must happen before CtorInit nodes are removed
151 /// (currently by FixInit)
152 static void insert( std::list< Declaration * > & translationUnit );
153
154 typedef std::list< ObjectDecl * > OrderedDecls;
155 typedef std::list< OrderedDecls > OrderedDeclsStack;
156
157 InsertDtors( PassVisitor<LabelFinder> & finder ) : finder( finder ), labelVars( finder.pass.vars ) {}
158
159 typedef ObjDeclCollector Parent;
160 using Parent::previsit;
161
162 void previsit( ObjectDecl * objDecl );
163 void previsit( FunctionDecl * funcDecl );
164
165 void previsit( CompoundStmt * compoundStmt );
166 void postvisit( CompoundStmt * compoundStmt );
167 void previsit( ReturnStmt * returnStmt );
168 void previsit( BranchStmt * stmt );
169 private:
170 void handleGoto( BranchStmt * stmt );
171
172 PassVisitor<LabelFinder> & finder;
173 LabelFinder::LabelMap & labelVars;
174 OrderedDeclsStack reverseDeclOrder;
175 };
176
177 class FixInit : public WithStmtsToAdd {
178 public:
179 /// expand each object declaration to use its constructor after it is declared.
180 static void fixInitializers( std::list< Declaration * > &translationUnit );
181
182 DeclarationWithType * postmutate( ObjectDecl *objDecl );
183
184 std::list< Declaration * > staticDtorDecls;
185 };
186
187 class FixCopyCtors final : public WithStmtsToAdd, public WithShortCircuiting, public WithVisitorRef<FixCopyCtors> {
188 public:
189 FixCopyCtors( UnqCount & unqCount ) : unqCount( unqCount ){}
190 /// expand ImplicitCopyCtorExpr nodes into the temporary declarations, copy constructors, call expression,
191 /// and destructors
192 static void fixCopyCtors( std::list< Declaration * > &translationUnit, UnqCount & unqCount );
193
194 Expression * postmutate( ImplicitCopyCtorExpr * impCpCtorExpr );
195 void premutate( StmtExpr * stmtExpr );
196 void premutate( UniqueExpr * unqExpr );
197
198 UnqCount & unqCount;
199 };
200
201 struct GenStructMemberCalls final : public WithGuards, public WithShortCircuiting, public WithIndexer {
202 /// generate default/copy ctor and dtor calls for user-defined struct ctor/dtors
203 /// for any member that is missing a corresponding ctor/dtor call.
204 /// error if a member is used before constructed
205 static void generate( std::list< Declaration * > & translationUnit );
206
207 void previsit( FunctionDecl * funcDecl );
208 void postvisit( FunctionDecl * funcDecl );
209
210 void previsit( MemberExpr * memberExpr );
211 void previsit( ApplicationExpr * appExpr );
212
213 SemanticError errors;
214 private:
215 template< typename... Params >
216 void emit( CodeLocation, const Params &... params );
217
218 FunctionDecl * function = 0;
219 std::set< DeclarationWithType * > unhandled;
220 std::map< DeclarationWithType *, CodeLocation > usedUninit;
221 ObjectDecl * thisParam = 0;
222 bool isCtor = false; // true if current function is a constructor
223 StructDecl * structDecl = 0;
224 };
225
226 // very simple resolver-like mutator class - used to
227 // resolve UntypedExprs that are found within newly
228 // generated constructor/destructor calls
229 class MutatingResolver final : public Mutator {
230 public:
231 MutatingResolver( SymTab::Indexer & indexer ) : indexer( indexer ) {}
232
233 using Mutator::mutate;
234 virtual DeclarationWithType* mutate( ObjectDecl *objectDecl ) override;
235 virtual Expression* mutate( UntypedExpr *untypedExpr ) override;
236
237 private:
238 SymTab::Indexer & indexer;
239 };
240
241 struct FixCtorExprs final : public WithDeclsToAdd, public WithIndexer {
242 /// expands ConstructorExpr nodes into comma expressions, using a temporary for the first argument
243 static void fix( std::list< Declaration * > & translationUnit );
244
245 Expression * postmutate( ConstructorExpr * ctorExpr );
246 };
247 } // namespace
248
249 void fix( std::list< Declaration * > & translationUnit, const std::string & filename, bool inLibrary ) {
250 // fixes ConstructorInit for global variables. should happen before fixInitializers.
251 InitTweak::fixGlobalInit( translationUnit, filename, inLibrary );
252
253 UnqCount unqCount;
254
255 InsertImplicitCalls::insert( translationUnit );
256 ResolveCopyCtors::resolveImplicitCalls( translationUnit, unqCount );
257 InsertDtors::insert( translationUnit );
258 FixInit::fixInitializers( translationUnit );
259
260 // FixCopyCtors must happen after FixInit, so that destructors are placed correctly
261 FixCopyCtors::fixCopyCtors( translationUnit, unqCount );
262
263 GenStructMemberCalls::generate( translationUnit );
264 // xxx - ctor expansion currently has to be after FixCopyCtors, because there is currently a
265 // hack in the way untyped assignments are generated, where the first argument cannot have
266 // its address taken because of the way codegeneration handles UntypedExpr vs. ApplicationExpr.
267 // Thus such assignment exprs must never pushed through expression resolution (and thus should
268 // not go through the FixCopyCtors pass), otherwise they will fail -- guaranteed.
269 // Also needs to happen after GenStructMemberCalls, since otherwise member constructors exprs
270 // don't look right, and a member can be constructed more than once.
271 FixCtorExprs::fix( translationUnit );
272 }
273
274 namespace {
275 void InsertImplicitCalls::insert( std::list< Declaration * > & translationUnit ) {
276 PassVisitor<InsertImplicitCalls> inserter;
277 mutateAll( translationUnit, inserter );
278 }
279
280 void ResolveCopyCtors::resolveImplicitCalls( std::list< Declaration * > & translationUnit, UnqCount & unqCount ) {
281 PassVisitor<ResolveCopyCtors> resolver( unqCount );
282 acceptAll( translationUnit, resolver );
283 }
284
285 void FixInit::fixInitializers( std::list< Declaration * > & translationUnit ) {
286 PassVisitor<FixInit> fixer;
287
288 // can't use mutateAll, because need to insert declarations at top-level
289 // can't use DeclMutator, because sometimes need to insert IfStmt, etc.
290 SemanticError errors;
291 for ( std::list< Declaration * >::iterator i = translationUnit.begin(); i != translationUnit.end(); ++i ) {
292 try {
293 *i = maybeMutate( *i, fixer );
294 translationUnit.splice( i, fixer.pass.staticDtorDecls );
295 } catch( SemanticError &e ) {
296 e.set_location( (*i)->location );
297 errors.append( e );
298 } // try
299 } // for
300 if ( ! errors.isEmpty() ) {
301 throw errors;
302 } // if
303 }
304
305 void InsertDtors::insert( std::list< Declaration * > & translationUnit ) {
306 PassVisitor<LabelFinder> finder;
307 PassVisitor<InsertDtors> inserter( finder );
308 acceptAll( translationUnit, inserter );
309 }
310
311 void FixCopyCtors::fixCopyCtors( std::list< Declaration * > & translationUnit, UnqCount & unqCount ) {
312 PassVisitor<FixCopyCtors> fixer( unqCount );
313 mutateAll( translationUnit, fixer );
314 }
315
316 void GenStructMemberCalls::generate( std::list< Declaration * > & translationUnit ) {
317 PassVisitor<GenStructMemberCalls> warner;
318 acceptAll( translationUnit, warner );
319 }
320
321 void FixCtorExprs::fix( std::list< Declaration * > & translationUnit ) {
322 PassVisitor<FixCtorExprs> fixer;
323 mutateAll( translationUnit, fixer );
324 }
325
326 Expression * InsertImplicitCalls::postmutate( ApplicationExpr * appExpr ) {
327 assert( appExpr );
328
329 if ( VariableExpr * function = dynamic_cast< VariableExpr * > ( appExpr->get_function() ) ) {
330 if ( LinkageSpec::isBuiltin( function->get_var()->get_linkage() ) ) {
331 // optimization: don't need to copy construct in order to call intrinsic functions
332 return appExpr;
333 } else if ( DeclarationWithType * funcDecl = dynamic_cast< DeclarationWithType * > ( function->get_var() ) ) {
334 FunctionType * ftype = dynamic_cast< FunctionType * >( GenPoly::getFunctionType( funcDecl->get_type() ) );
335 assertf( ftype, "Function call without function type: %s", toString( funcDecl ).c_str() );
336 if ( CodeGen::isConstructor( funcDecl->get_name() ) && ftype->get_parameters().size() == 2 ) {
337 Type * t1 = getPointerBase( ftype->get_parameters().front()->get_type() );
338 Type * t2 = ftype->get_parameters().back()->get_type();
339 assert( t1 );
340
341 if ( ResolvExpr::typesCompatible( t1, t2, SymTab::Indexer() ) ) {
342 // optimization: don't need to copy construct in order to call a copy constructor
343 return appExpr;
344 } // if
345 } else if ( CodeGen::isDestructor( funcDecl->get_name() ) ) {
346 // correctness: never copy construct arguments to a destructor
347 return appExpr;
348 } // if
349 } // if
350 } // if
351 CP_CTOR_PRINT( std::cerr << "InsertImplicitCalls: adding a wrapper " << appExpr << std::endl; )
352
353 // wrap each function call so that it is easy to identify nodes that have to be copy constructed
354 ImplicitCopyCtorExpr * expr = new ImplicitCopyCtorExpr( appExpr );
355 // Move the type substitution to the new top-level, if it is attached to the appExpr.
356 // Ensure it is not deleted with the ImplicitCopyCtorExpr by removing it before deletion.
357 // The substitution is needed to obtain the type of temporary variables so that copy constructor
358 // calls can be resolved.
359 assert( env );
360 std::swap( expr->env, appExpr->env );
361 return expr;
362 }
363
364 bool ResolveCopyCtors::skipCopyConstruct( Type * type ) { return ! isConstructable( type ); }
365
366 Expression * ResolveCopyCtors::makeCtorDtor( const std::string & fname, ObjectDecl * var, Expression * cpArg ) {
367 assert( var );
368 // arrays are not copy constructed, so this should always be an ExprStmt
369 ImplicitCtorDtorStmt * stmt = genCtorDtor( fname, var, cpArg );
370 ExprStmt * exprStmt = strict_dynamic_cast< ExprStmt * >( stmt->get_callStmt() );
371 Expression * untyped = exprStmt->get_expr();
372
373 // resolve copy constructor
374 // should only be one alternative for copy ctor and dtor expressions, since all arguments are fixed
375 // (VariableExpr and already resolved expression)
376 CP_CTOR_PRINT( std::cerr << "ResolvingCtorDtor " << untyped << std::endl; )
377 Expression * resolved = ResolvExpr::findVoidExpression( untyped, indexer );
378 assert( resolved );
379 if ( resolved->get_env() ) {
380 // Extract useful information and discard new environments. Keeping them causes problems in PolyMutator passes.
381 env->add( *resolved->get_env() );
382 delete resolved->get_env();
383 resolved->set_env( nullptr );
384 } // if
385
386 delete stmt;
387 return resolved;
388 }
389
390 void ResolveCopyCtors::copyConstructArg( Expression *& arg, ImplicitCopyCtorExpr * impCpCtorExpr ) {
391 static UniqueName tempNamer("_tmp_cp");
392 assert( env );
393 CP_CTOR_PRINT( std::cerr << "Type Substitution: " << *env << std::endl; )
394 assert( arg->has_result() );
395 Type * result = arg->get_result();
396 if ( skipCopyConstruct( result ) ) return; // skip certain non-copyable types
397
398 // type may involve type variables, so apply type substitution to get temporary variable's actual type
399 result = result->clone();
400 env->apply( result );
401 ObjectDecl * tmp = ObjectDecl::newObject( "__tmp", result, nullptr );
402 tmp->get_type()->set_const( false );
403
404 // create and resolve copy constructor
405 CP_CTOR_PRINT( std::cerr << "makeCtorDtor for an argument" << std::endl; )
406 Expression * cpCtor = makeCtorDtor( "?{}", tmp, arg );
407
408 if ( ApplicationExpr * appExpr = dynamic_cast< ApplicationExpr * >( cpCtor ) ) {
409 // if the chosen constructor is intrinsic, the copy is unnecessary, so
410 // don't create the temporary and don't call the copy constructor
411 VariableExpr * function = dynamic_cast< VariableExpr * >( appExpr->get_function() );
412 assert( function );
413 if ( function->get_var()->get_linkage() == LinkageSpec::Intrinsic ) return;
414 }
415
416 // set a unique name for the temporary once it's certain the call is necessary
417 tmp->name = tempNamer.newName();
418
419 // replace argument to function call with temporary
420 arg = new CommaExpr( cpCtor, new VariableExpr( tmp ) );
421 impCpCtorExpr->get_tempDecls().push_back( tmp );
422 impCpCtorExpr->get_dtors().push_front( makeCtorDtor( "^?{}", tmp ) );
423 }
424
425 void ResolveCopyCtors::destructRet( ObjectDecl * ret, ImplicitCopyCtorExpr * impCpCtorExpr ) {
426 impCpCtorExpr->get_dtors().push_front( makeCtorDtor( "^?{}", ret ) );
427 }
428
429 void ResolveCopyCtors::postvisit( ImplicitCopyCtorExpr *impCpCtorExpr ) {
430 CP_CTOR_PRINT( std::cerr << "ResolveCopyCtors: " << impCpCtorExpr << std::endl; )
431
432 ApplicationExpr * appExpr = impCpCtorExpr->get_callExpr();
433
434 // take each argument and attempt to copy construct it.
435 for ( Expression * & arg : appExpr->get_args() ) {
436 copyConstructArg( arg, impCpCtorExpr );
437 } // for
438
439 // each return value from the call needs to be connected with an ObjectDecl at the call site, which is
440 // initialized with the return value and is destructed later
441 // xxx - handle named return values?
442 Type * result = appExpr->get_result();
443 if ( ! result->isVoid() ) {
444 static UniqueName retNamer("_tmp_cp_ret");
445 result = result->clone();
446 env->apply( result );
447 ObjectDecl * ret = ObjectDecl::newObject( retNamer.newName(), result, nullptr );
448 ret->get_type()->set_const( false );
449 impCpCtorExpr->get_returnDecls().push_back( ret );
450 CP_CTOR_PRINT( std::cerr << "makeCtorDtor for a return" << std::endl; )
451 if ( ! dynamic_cast< ReferenceType * >( result ) ) {
452 // destructing reference returns is bad because it can cause multiple destructor calls to the same object - the returned object is not a temporary
453 destructRet( ret, impCpCtorExpr );
454 }
455 } // for
456 CP_CTOR_PRINT( std::cerr << "after Resolving: " << impCpCtorExpr << std::endl; )
457 }
458
459 void ResolveCopyCtors::postvisit( StmtExpr * stmtExpr ) {
460 assert( env );
461 assert( stmtExpr->get_result() );
462 Type * result = stmtExpr->get_result();
463 if ( ! result->isVoid() ) {
464 static UniqueName retNamer("_tmp_stmtexpr_ret");
465
466 // create variable that will hold the result of the stmt expr
467 result = result->clone();
468 env->apply( result );
469 ObjectDecl * ret = ObjectDecl::newObject( retNamer.newName(), result, nullptr );
470 ret->get_type()->set_const( false );
471 stmtExpr->get_returnDecls().push_front( ret );
472
473 // must have a non-empty body, otherwise it wouldn't have a result
474 CompoundStmt * body = stmtExpr->get_statements();
475 assert( ! body->get_kids().empty() );
476 // must be an ExprStmt, otherwise it wouldn't have a result
477 ExprStmt * last = strict_dynamic_cast< ExprStmt * >( body->get_kids().back() );
478 last->set_expr( makeCtorDtor( "?{}", ret, last->get_expr() ) );
479
480 stmtExpr->get_dtors().push_front( makeCtorDtor( "^?{}", ret ) );
481 } // if
482 }
483
484 void ResolveCopyCtors::previsit( UniqueExpr * unqExpr ) {
485 unqCount[ unqExpr->get_id() ]++; // count the number of unique expressions for each ID
486 if ( vars.count( unqExpr->get_id() ) ) {
487 // xxx - hack to prevent double-handling of unique exprs, otherwise too many temporary variables and destructors are generated
488 visit_children = false;
489 }
490 }
491
492 void ResolveCopyCtors::postvisit( UniqueExpr * unqExpr ) {
493 if ( vars.count( unqExpr->get_id() ) ) {
494 // xxx - hack to prevent double-handling of unique exprs, otherwise too many temporary variables and destructors are generated
495 return;
496 }
497
498 // it should never be necessary to wrap a void-returning expression in a UniqueExpr - if this assumption changes, this needs to be rethought
499 assert( unqExpr->get_result() );
500 if ( ImplicitCopyCtorExpr * impCpCtorExpr = dynamic_cast<ImplicitCopyCtorExpr*>( unqExpr->get_expr() ) ) {
501 // note the variable used as the result from the call
502 assert( impCpCtorExpr->get_result() && impCpCtorExpr->get_returnDecls().size() == 1 );
503 unqExpr->set_var( new VariableExpr( impCpCtorExpr->get_returnDecls().front() ) );
504 } else {
505 // expr isn't a call expr, so create a new temporary variable to use to hold the value of the unique expression
506 unqExpr->set_object( ObjectDecl::newObject( toString("_unq", unqExpr->get_id()), unqExpr->get_result()->clone(), nullptr ) );
507 unqExpr->set_var( new VariableExpr( unqExpr->get_object() ) );
508 }
509 vars.insert( unqExpr->get_id() );
510 }
511
512 Expression * FixCopyCtors::postmutate( ImplicitCopyCtorExpr * impCpCtorExpr ) {
513 CP_CTOR_PRINT( std::cerr << "FixCopyCtors: " << impCpCtorExpr << std::endl; )
514
515 std::list< ObjectDecl * > & tempDecls = impCpCtorExpr->get_tempDecls();
516 std::list< ObjectDecl * > & returnDecls = impCpCtorExpr->get_returnDecls();
517 std::list< Expression * > & dtors = impCpCtorExpr->get_dtors();
518
519 // add all temporary declarations and their constructors
520 for ( ObjectDecl * obj : tempDecls ) {
521 stmtsToAddBefore.push_back( new DeclStmt( noLabels, obj ) );
522 } // for
523 for ( ObjectDecl * obj : returnDecls ) {
524 stmtsToAddBefore.push_back( new DeclStmt( noLabels, obj ) );
525 } // for
526
527 // add destructors after current statement
528 for ( Expression * dtor : dtors ) {
529 stmtsToAddAfter.push_back( new ExprStmt( noLabels, dtor ) );
530 } // for
531
532 ObjectDecl * returnDecl = returnDecls.empty() ? nullptr : returnDecls.front();
533 Expression * callExpr = impCpCtorExpr->get_callExpr();
534
535 CP_CTOR_PRINT( std::cerr << "Coming out the back..." << impCpCtorExpr << std::endl; )
536
537 // detach fields from wrapper node so that it can be deleted without deleting too much
538 dtors.clear();
539 tempDecls.clear();
540 returnDecls.clear();
541 impCpCtorExpr->set_callExpr( nullptr );
542 std::swap( impCpCtorExpr->env, callExpr->env );
543 assert( impCpCtorExpr->env == nullptr );
544 delete impCpCtorExpr;
545
546 if ( returnDecl ) {
547 UntypedExpr * assign = new UntypedExpr( new NameExpr( "?=?" ) );
548 assign->get_args().push_back( new VariableExpr( returnDecl ) );
549 assign->get_args().push_back( callExpr );
550 // know the result type of the assignment is the type of the LHS (minus the pointer), so
551 // add that onto the assignment expression so that later steps have the necessary information
552 assign->set_result( returnDecl->get_type()->clone() );
553
554 Expression * retExpr = new CommaExpr( assign, new VariableExpr( returnDecl ) );
555 // move env from callExpr to retExpr
556 retExpr->set_env( callExpr->get_env() );
557 callExpr->set_env( nullptr );
558 return retExpr;
559 } else {
560 return callExpr;
561 } // if
562 }
563
564 void FixCopyCtors::premutate( StmtExpr * stmtExpr ) {
565 // function call temporaries should be placed at statement-level, rather than nested inside of a new statement expression,
566 // since temporaries can be shared across sub-expressions, e.g.
567 // [A, A] f();
568 // g([A] x, [A] y);
569 // g(f());
570 // f is executed once, so the return temporary is shared across the tuple constructors for x and y.
571 // Explicitly mutating children instead of mutating the inner compound statment forces the temporaries to be added
572 // to the outer context, rather than inside of the statement expression.
573 visit_children = false;
574 std::list< Statement * > & stmts = stmtExpr->get_statements()->get_kids();
575 for ( Statement *& stmt : stmts ) {
576 stmt = stmt->acceptMutator( *visitor );
577 } // for
578 assert( stmtExpr->get_result() );
579 Type * result = stmtExpr->get_result();
580 if ( ! result->isVoid() ) {
581 for ( ObjectDecl * obj : stmtExpr->get_returnDecls() ) {
582 stmtsToAddBefore.push_back( new DeclStmt( noLabels, obj ) );
583 } // for
584 // add destructors after current statement
585 for ( Expression * dtor : stmtExpr->get_dtors() ) {
586 stmtsToAddAfter.push_back( new ExprStmt( noLabels, dtor ) );
587 } // for
588 // must have a non-empty body, otherwise it wouldn't have a result
589 assert( ! stmts.empty() );
590 assert( ! stmtExpr->get_returnDecls().empty() );
591 stmts.push_back( new ExprStmt( noLabels, new VariableExpr( stmtExpr->get_returnDecls().front() ) ) );
592 stmtExpr->get_returnDecls().clear();
593 stmtExpr->get_dtors().clear();
594 }
595 assert( stmtExpr->get_returnDecls().empty() );
596 assert( stmtExpr->get_dtors().empty() );
597 }
598
599 void FixCopyCtors::premutate( UniqueExpr * unqExpr ) {
600 visit_children = false;
601 unqCount[ unqExpr->get_id() ]--;
602 static std::unordered_map< int, std::list< Statement * > > dtors;
603 static std::unordered_map< int, UniqueExpr * > unqMap;
604 // has to be done to clean up ImplicitCopyCtorExpr nodes, even when this node was skipped in previous passes
605 if ( unqMap.count( unqExpr->get_id() ) ) {
606 // take data from other UniqueExpr to ensure consistency
607 delete unqExpr->get_expr();
608 unqExpr->set_expr( unqMap[unqExpr->get_id()]->get_expr()->clone() );
609 delete unqExpr->get_result();
610 unqExpr->set_result( maybeClone( unqExpr->get_expr()->get_result() ) );
611 if ( unqCount[ unqExpr->get_id() ] == 0 ) { // insert destructor after the last use of the unique expression
612 stmtsToAddAfter.splice( stmtsToAddAfter.end(), dtors[ unqExpr->get_id() ] );
613 }
614 return;
615 }
616 PassVisitor<FixCopyCtors> fixer( unqCount );
617 unqExpr->set_expr( unqExpr->get_expr()->acceptMutator( fixer ) ); // stmtexprs contained should not be separately fixed, so this must occur after the lookup
618 stmtsToAddBefore.splice( stmtsToAddBefore.end(), fixer.pass.stmtsToAddBefore );
619 unqMap[unqExpr->get_id()] = unqExpr;
620 if ( unqCount[ unqExpr->get_id() ] == 0 ) { // insert destructor after the last use of the unique expression
621 stmtsToAddAfter.splice( stmtsToAddAfter.end(), dtors[ unqExpr->get_id() ] );
622 } else { // remember dtors for last instance of unique expr
623 dtors[ unqExpr->get_id() ] = fixer.pass.stmtsToAddAfter;
624 }
625 return;
626 }
627
628 DeclarationWithType *FixInit::postmutate( ObjectDecl *objDecl ) {
629 // since this removes the init field from objDecl, it must occur after children are mutated (i.e. postmutate)
630 if ( ConstructorInit * ctorInit = dynamic_cast< ConstructorInit * >( objDecl->get_init() ) ) {
631 // a decision should have been made by the resolver, so ctor and init are not both non-NULL
632 assert( ! ctorInit->get_ctor() || ! ctorInit->get_init() );
633 if ( Statement * ctor = ctorInit->get_ctor() ) {
634 if ( objDecl->get_storageClasses().is_static ) {
635 // originally wanted to take advantage of gcc nested functions, but
636 // we get memory errors with this approach. To remedy this, the static
637 // variable is hoisted when the destructor needs to be called.
638 //
639 // generate:
640 // static T __objName_static_varN;
641 // void __objName_dtor_atexitN() {
642 // __dtor__...;
643 // }
644 // int f(...) {
645 // ...
646 // static bool __objName_uninitialized = true;
647 // if (__objName_uninitialized) {
648 // __ctor(__objName);
649 // __objName_uninitialized = false;
650 // atexit(__objName_dtor_atexitN);
651 // }
652 // ...
653 // }
654
655 static UniqueName dtorCallerNamer( "_dtor_atexit" );
656
657 // static bool __objName_uninitialized = true
658 BasicType * boolType = new BasicType( Type::Qualifiers(), BasicType::Bool );
659 SingleInit * boolInitExpr = new SingleInit( new ConstantExpr( Constant::from_int( 1 ) ) );
660 ObjectDecl * isUninitializedVar = new ObjectDecl( objDecl->get_mangleName() + "_uninitialized", Type::StorageClasses( Type::Static ), LinkageSpec::Cforall, 0, boolType, boolInitExpr );
661 isUninitializedVar->fixUniqueId();
662
663 // __objName_uninitialized = false;
664 UntypedExpr * setTrue = new UntypedExpr( new NameExpr( "?=?" ) );
665 setTrue->get_args().push_back( new VariableExpr( isUninitializedVar ) );
666 setTrue->get_args().push_back( new ConstantExpr( Constant::from_int( 0 ) ) );
667
668 // generate body of if
669 CompoundStmt * initStmts = new CompoundStmt( noLabels );
670 std::list< Statement * > & body = initStmts->get_kids();
671 body.push_back( ctor );
672 body.push_back( new ExprStmt( noLabels, setTrue ) );
673
674 // put it all together
675 IfStmt * ifStmt = new IfStmt( noLabels, new VariableExpr( isUninitializedVar ), initStmts, 0 );
676 stmtsToAddAfter.push_back( new DeclStmt( noLabels, isUninitializedVar ) );
677 stmtsToAddAfter.push_back( ifStmt );
678
679 Statement * dtor = ctorInit->get_dtor();
680 objDecl->set_init( nullptr );
681 ctorInit->set_ctor( nullptr );
682 ctorInit->set_dtor( nullptr );
683 if ( dtor ) {
684 // if the object has a non-trivial destructor, have to
685 // hoist it and the object into the global space and
686 // call the destructor function with atexit.
687
688 Statement * dtorStmt = dtor->clone();
689
690 // void __objName_dtor_atexitN(...) {...}
691 FunctionDecl * dtorCaller = new FunctionDecl( objDecl->get_mangleName() + dtorCallerNamer.newName(), Type::StorageClasses( Type::Static ), LinkageSpec::C, new FunctionType( Type::Qualifiers(), false ), new CompoundStmt( noLabels ) );
692 dtorCaller->fixUniqueId();
693 dtorCaller->get_statements()->push_back( dtorStmt );
694
695 // atexit(dtor_atexit);
696 UntypedExpr * callAtexit = new UntypedExpr( new NameExpr( "atexit" ) );
697 callAtexit->get_args().push_back( new VariableExpr( dtorCaller ) );
698
699 body.push_back( new ExprStmt( noLabels, callAtexit ) );
700
701 // hoist variable and dtor caller decls to list of decls that will be added into global scope
702 staticDtorDecls.push_back( objDecl );
703 staticDtorDecls.push_back( dtorCaller );
704
705 // need to rename object uniquely since it now appears
706 // at global scope and there could be multiple function-scoped
707 // static variables with the same name in different functions.
708 // Note: it isn't sufficient to modify only the mangleName, because
709 // then subsequent Indexer passes can choke on seeing the object's name
710 // if another object has the same name and type. An unfortunate side-effect
711 // of renaming the object is that subsequent NameExprs may fail to resolve,
712 // but there shouldn't be any remaining past this point.
713 static UniqueName staticNamer( "_static_var" );
714 objDecl->set_name( objDecl->get_name() + staticNamer.newName() );
715 objDecl->set_mangleName( SymTab::Mangler::mangle( objDecl ) );
716
717 // xxx - temporary hack: need to return a declaration, but want to hoist the current object out of this scope
718 // create a new object which is never used
719 static UniqueName dummyNamer( "_dummy" );
720 ObjectDecl * dummy = new ObjectDecl( dummyNamer.newName(), Type::StorageClasses( Type::Static ), LinkageSpec::Cforall, 0, new PointerType( Type::Qualifiers(), new VoidType( Type::Qualifiers() ) ), 0, std::list< Attribute * >{ new Attribute("unused") } );
721 delete ctorInit;
722 return dummy;
723 }
724 } else {
725 ImplicitCtorDtorStmt * implicit = strict_dynamic_cast< ImplicitCtorDtorStmt * > ( ctor );
726 ExprStmt * ctorStmt = dynamic_cast< ExprStmt * >( implicit->get_callStmt() );
727 ApplicationExpr * ctorCall = nullptr;
728 if ( ctorStmt && (ctorCall = isIntrinsicCallExpr( ctorStmt->get_expr() )) && ctorCall->get_args().size() == 2 ) {
729 // clean up intrinsic copy constructor calls by making them into SingleInits
730 objDecl->set_init( new SingleInit( ctorCall->get_args().back() ) );
731 ctorCall->get_args().pop_back();
732 } else {
733 stmtsToAddAfter.push_back( ctor );
734 objDecl->set_init( nullptr );
735 ctorInit->set_ctor( nullptr );
736 }
737 } // if
738 } else if ( Initializer * init = ctorInit->get_init() ) {
739 objDecl->set_init( init );
740 ctorInit->set_init( nullptr );
741 } else {
742 // no constructor and no initializer, which is okay
743 objDecl->set_init( nullptr );
744 } // if
745 delete ctorInit;
746 } // if
747 return objDecl;
748 }
749
750 void ObjDeclCollector::previsit( CompoundStmt * ) {
751 GuardValue( curVars );
752 }
753
754 void ObjDeclCollector::previsit( DeclStmt * stmt ) {
755 // keep track of all variables currently in scope
756 if ( ObjectDecl * objDecl = dynamic_cast< ObjectDecl * > ( stmt->get_decl() ) ) {
757 curVars.push_back( objDecl );
758 } // if
759 }
760
761 void LabelFinder::previsit( Statement * stmt ) {
762 // for each label, remember the variables in scope at that label.
763 for ( Label l : stmt->get_labels() ) {
764 vars[l] = curVars;
765 } // for
766 }
767
768 void LabelFinder::previsit( CompoundStmt * stmt ) {
769 previsit( (Statement *)stmt );
770 Parent::previsit( stmt );
771 }
772
773 void LabelFinder::previsit( DeclStmt * stmt ) {
774 previsit( (Statement *)stmt );
775 Parent::previsit( stmt );
776 }
777
778
779 template<typename Iterator, typename OutputIterator>
780 void insertDtors( Iterator begin, Iterator end, OutputIterator out ) {
781 for ( Iterator it = begin ; it != end ; ++it ) {
782 // extract destructor statement from the object decl and insert it into the output. Note that this is
783 // only called on lists of non-static objects with implicit non-intrinsic dtors, so if the user manually
784 // calls an intrinsic dtor then the call must (and will) still be generated since the argument may
785 // contain side effects.
786 ObjectDecl * objDecl = *it;
787 ConstructorInit * ctorInit = dynamic_cast< ConstructorInit * >( objDecl->get_init() );
788 assert( ctorInit && ctorInit->get_dtor() );
789 *out++ = ctorInit->get_dtor()->clone();
790 } // for
791 }
792
793 void InsertDtors::previsit( ObjectDecl * objDecl ) {
794 // remember non-static destructed objects so that their destructors can be inserted later
795 if ( ! objDecl->get_storageClasses().is_static ) {
796 if ( ConstructorInit * ctorInit = dynamic_cast< ConstructorInit * >( objDecl->get_init() ) ) {
797 // a decision should have been made by the resolver, so ctor and init are not both non-NULL
798 assert( ! ctorInit->get_ctor() || ! ctorInit->get_init() );
799 Statement * dtor = ctorInit->get_dtor();
800 // don't need to call intrinsic dtor, because it does nothing, but
801 // non-intrinsic dtors must be called
802 if ( dtor && ! isIntrinsicSingleArgCallStmt( dtor ) ) {
803 // set dtor location to the object's location for error messages
804 ctorInit->dtor->location = objDecl->location;
805 reverseDeclOrder.front().push_front( objDecl );
806 } // if
807 } // if
808 } // if
809 }
810
811 void InsertDtors::previsit( FunctionDecl * funcDecl ) {
812 // each function needs to have its own set of labels
813 GuardValue( labelVars );
814 labelVars.clear();
815 maybeAccept( funcDecl->type, finder );
816 maybeAccept( funcDecl->statements, finder );
817
818 // all labels for this function have been collected, insert destructors as appropriate via implicit recursion.
819 }
820
821 void InsertDtors::previsit( CompoundStmt * compoundStmt ) {
822 // visit statements - this will also populate reverseDeclOrder list. don't want to dump all destructors
823 // when block is left, just the destructors associated with variables defined in this block, so push a new
824 // list to the top of the stack so that we can differentiate scopes
825 reverseDeclOrder.push_front( OrderedDecls() );
826 Parent::previsit( compoundStmt );
827 }
828
829 void InsertDtors::postvisit( CompoundStmt * compoundStmt ) {
830 // add destructors for the current scope that we're exiting, unless the last statement is a return, which
831 // causes unreachable code warnings
832 std::list< Statement * > & statements = compoundStmt->get_kids();
833 if ( ! statements.empty() && ! dynamic_cast< ReturnStmt * >( statements.back() ) ) {
834 insertDtors( reverseDeclOrder.front().begin(), reverseDeclOrder.front().end(), back_inserter( statements ) );
835 }
836 reverseDeclOrder.pop_front();
837 }
838
839 void InsertDtors::previsit( ReturnStmt * ) {
840 // return exits all scopes, so dump destructors for all scopes
841 for ( OrderedDecls & od : reverseDeclOrder ) {
842 insertDtors( od.begin(), od.end(), back_inserter( stmtsToAddBefore ) );
843 } // for
844 }
845
846 // Handle break/continue/goto in the same manner as C++. Basic idea: any objects that are in scope at the
847 // BranchStmt but not at the labelled (target) statement must be destructed. If there are any objects in scope
848 // at the target location but not at the BranchStmt then those objects would be uninitialized so notify the user
849 // of the error. See C++ Reference 6.6 Jump Statements for details.
850 void InsertDtors::handleGoto( BranchStmt * stmt ) {
851 // can't do anything for computed goto
852 if ( stmt->computedTarget ) return;
853
854 assertf( stmt->get_target() != "", "BranchStmt missing a label: %s", toString( stmt ).c_str() );
855 // S_L = lvars = set of objects in scope at label definition
856 // S_G = curVars = set of objects in scope at goto statement
857 ObjectSet & lvars = labelVars[ stmt->get_target() ];
858
859 DTOR_PRINT(
860 std::cerr << "at goto label: " << stmt->get_target().get_name() << std::endl;
861 std::cerr << "S_G = " << printSet( curVars ) << std::endl;
862 std::cerr << "S_L = " << printSet( lvars ) << std::endl;
863 )
864
865 ObjectSet diff;
866 // S_L-S_G results in set of objects whose construction is skipped - it's an error if this set is non-empty
867 std::set_difference( lvars.begin(), lvars.end(), curVars.begin(), curVars.end(), std::inserter( diff, diff.begin() ) );
868 DTOR_PRINT(
869 std::cerr << "S_L-S_G = " << printSet( diff ) << std::endl;
870 )
871 if ( ! diff.empty() ) {
872 throw SemanticError( std::string("jump to label '") + stmt->get_target().get_name() + "' crosses initialization of " + (*diff.begin())->get_name() + " ", stmt );
873 } // if
874 // S_G-S_L results in set of objects that must be destructed
875 diff.clear();
876 std::set_difference( curVars.begin(), curVars.end(), lvars.begin(), lvars.end(), std::inserter( diff, diff.end() ) );
877 DTOR_PRINT(
878 std::cerr << "S_G-S_L = " << printSet( diff ) << std::endl;
879 )
880 if ( ! diff.empty() ) {
881 // create an auxilliary set for fast lookup -- can't make diff a set, because diff ordering should be consistent for error messages.
882 std::unordered_set<ObjectDecl *> needsDestructor( diff.begin(), diff.end() );
883
884 // go through decl ordered list of objectdecl. for each element that occurs in diff, output destructor
885 OrderedDecls ordered;
886 for ( OrderedDecls & rdo : reverseDeclOrder ) {
887 // add elements from reverseDeclOrder into ordered if they occur in diff - it is key that this happens in reverse declaration order.
888 copy_if( rdo.begin(), rdo.end(), back_inserter( ordered ), [&]( ObjectDecl * objDecl ) { return needsDestructor.count( objDecl ); } );
889 } // for
890 insertDtors( ordered.begin(), ordered.end(), back_inserter( stmtsToAddBefore ) );
891 } // if
892 }
893
894 void InsertDtors::previsit( BranchStmt * stmt ) {
895 switch( stmt->get_type() ) {
896 case BranchStmt::Continue:
897 case BranchStmt::Break:
898 // could optimize the break/continue case, because the S_L-S_G check is unnecessary (this set should
899 // always be empty), but it serves as a small sanity check.
900 case BranchStmt::Goto:
901 handleGoto( stmt );
902 break;
903 default:
904 assert( false );
905 } // switch
906 }
907
908 bool checkWarnings( FunctionDecl * funcDecl ) {
909 // only check for warnings if the current function is a user-defined
910 // constructor or destructor
911 if ( ! funcDecl ) return false;
912 if ( ! funcDecl->get_statements() ) return false;
913 return CodeGen::isCtorDtor( funcDecl->get_name() ) && ! LinkageSpec::isOverridable( funcDecl->get_linkage() );
914 }
915
916 void GenStructMemberCalls::previsit( FunctionDecl * funcDecl ) {
917 GuardValue( funcDecl );
918 GuardValue( unhandled );
919 GuardValue( usedUninit );
920 GuardValue( thisParam );
921 GuardValue( isCtor );
922 GuardValue( structDecl );
923 errors = SemanticError(); // clear previous errors
924
925 // need to start with fresh sets
926 unhandled.clear();
927 usedUninit.clear();
928
929 function = funcDecl;
930 isCtor = CodeGen::isConstructor( function->get_name() );
931 if ( checkWarnings( function ) ) {
932 FunctionType * type = function->get_functionType();
933 assert( ! type->get_parameters().empty() );
934 thisParam = strict_dynamic_cast< ObjectDecl * >( type->get_parameters().front() );
935 Type * thisType = getPointerBase( thisParam->get_type() );
936 StructInstType * structType = dynamic_cast< StructInstType * >( thisType );
937 if ( structType ) {
938 structDecl = structType->get_baseStruct();
939 for ( Declaration * member : structDecl->get_members() ) {
940 if ( ObjectDecl * field = dynamic_cast< ObjectDecl * >( member ) ) {
941 // record all of the struct type's members that need to be constructed or
942 // destructed by the end of the function
943 unhandled.insert( field );
944 }
945 }
946 }
947 }
948 }
949
950 void addIds( SymTab::Indexer & indexer, const std::list< DeclarationWithType * > & decls ) {
951 for ( auto d : decls ) {
952 indexer.addId( d );
953 }
954 }
955
956 void addTypes( SymTab::Indexer & indexer, const std::list< TypeDecl * > & tds ) {
957 for ( auto td : tds ) {
958 indexer.addType( td );
959 addIds( indexer, td->assertions );
960 }
961 }
962
963 void GenStructMemberCalls::postvisit( FunctionDecl * funcDecl ) {
964 // remove the unhandled objects from usedUninit, because a call is inserted
965 // to handle them - only objects that are later constructed are used uninitialized.
966 std::map< DeclarationWithType *, CodeLocation > diff;
967 // need the comparator since usedUninit and unhandled have different types
968 struct comp_t {
969 typedef decltype(usedUninit)::value_type usedUninit_t;
970 typedef decltype(unhandled)::value_type unhandled_t;
971 bool operator()(usedUninit_t x, unhandled_t y) { return x.first < y; }
972 bool operator()(unhandled_t x, usedUninit_t y) { return x < y.first; }
973 } comp;
974 std::set_difference( usedUninit.begin(), usedUninit.end(), unhandled.begin(), unhandled.end(), std::inserter( diff, diff.begin() ), comp );
975 for ( auto p : diff ) {
976 DeclarationWithType * member = p.first;
977 CodeLocation loc = p.second;
978 // xxx - make error message better by also tracking the location that the object is constructed at?
979 emit( loc, "in ", CodeGen::genPrettyType( function->get_functionType(), function->get_name() ), ", field ", member->get_name(), " used before being constructed" );
980 }
981
982 if ( ! unhandled.empty() ) {
983 // need to explicitly re-add function parameters to the indexer in order to resolve copy constructors
984 auto guard = makeFuncGuard( [this]() { indexer.enterScope(); }, [this]() { indexer.leaveScope(); } );
985 addTypes( indexer, function->type->forall );
986 addIds( indexer, function->type->returnVals );
987 addIds( indexer, function->type->parameters );
988
989 // need to iterate through members in reverse in order for
990 // ctor/dtor statements to come out in the right order
991 for ( Declaration * member : reverseIterate( structDecl->get_members() ) ) {
992 DeclarationWithType * field = dynamic_cast< DeclarationWithType * >( member );
993 // skip non-DWT members
994 if ( ! field ) continue;
995 // skip non-constructable members
996 if ( ! tryConstruct( field ) ) continue;
997 // skip handled members
998 if ( ! unhandled.count( field ) ) continue;
999
1000 // insert and resolve default/copy constructor call for each field that's unhandled
1001 std::list< Statement * > stmt;
1002 Expression * arg2 = 0;
1003 if ( isCopyConstructor( function ) ) {
1004 // if copy ctor, need to pass second-param-of-this-function.field
1005 std::list< DeclarationWithType * > & params = function->get_functionType()->get_parameters();
1006 assert( params.size() == 2 );
1007 arg2 = new MemberExpr( field, new VariableExpr( params.back() ) );
1008 }
1009 InitExpander srcParam( arg2 );
1010 // cast away reference type and construct field.
1011 Expression * thisExpr = new CastExpr( new VariableExpr( thisParam ), thisParam->get_type()->stripReferences()->clone() );
1012 Expression * memberDest = new MemberExpr( field, thisExpr );
1013 SymTab::genImplicitCall( srcParam, memberDest, function->get_name(), back_inserter( stmt ), field, isCtor );
1014
1015 assert( stmt.size() <= 1 );
1016 if ( stmt.size() == 1 ) {
1017 Statement * callStmt = stmt.front();
1018
1019 MutatingResolver resolver( indexer );
1020 try {
1021 callStmt->acceptMutator( resolver );
1022 if ( isCtor ) {
1023 function->get_statements()->push_front( callStmt );
1024 } else {
1025 // destructor statements should be added at the end
1026 function->get_statements()->push_back( callStmt );
1027 }
1028 } catch ( SemanticError & error ) {
1029 emit( funcDecl->location, "in ", CodeGen::genPrettyType( function->get_functionType(), function->get_name() ), ", field ", field->get_name(), " not explicitly ", isCtor ? "constructed" : "destructed", " and no ", isCtor ? "default constructor" : "destructor", " found" );
1030 }
1031 }
1032 }
1033 }
1034 if (! errors.isEmpty()) {
1035 throw errors;
1036 }
1037 }
1038
1039 /// true if expr is effectively just the 'this' parameter
1040 bool isThisExpression( Expression * expr, DeclarationWithType * thisParam ) {
1041 // TODO: there are more complicated ways to pass 'this' to a constructor, e.g. &*, *&, etc.
1042 if ( VariableExpr * varExpr = dynamic_cast< VariableExpr * >( expr ) ) {
1043 return varExpr->get_var() == thisParam;
1044 } else if ( CastExpr * castExpr = dynamic_cast< CastExpr * > ( expr ) ) {
1045 return isThisExpression( castExpr->get_arg(), thisParam );
1046 }
1047 return false;
1048 }
1049
1050 /// returns a MemberExpr if expr is effectively just member access on the 'this' parameter, else nullptr
1051 MemberExpr * isThisMemberExpr( Expression * expr, DeclarationWithType * thisParam ) {
1052 if ( MemberExpr * memberExpr = dynamic_cast< MemberExpr * >( expr ) ) {
1053 if ( isThisExpression( memberExpr->get_aggregate(), thisParam ) ) {
1054 return memberExpr;
1055 }
1056 } else if ( CastExpr * castExpr = dynamic_cast< CastExpr * >( expr ) ) {
1057 return isThisMemberExpr( castExpr->get_arg(), thisParam );
1058 }
1059 return nullptr;
1060 }
1061
1062 void GenStructMemberCalls::previsit( ApplicationExpr * appExpr ) {
1063 if ( ! checkWarnings( function ) ) {
1064 visit_children = false;
1065 return;
1066 }
1067
1068 std::string fname = getFunctionName( appExpr );
1069 if ( fname == function->get_name() ) {
1070 // call to same kind of function
1071 Expression * firstParam = appExpr->get_args().front();
1072
1073 if ( isThisExpression( firstParam, thisParam ) ) {
1074 // if calling another constructor on thisParam, assume that function handles
1075 // all members - if it doesn't a warning will appear in that function.
1076 unhandled.clear();
1077 } else if ( MemberExpr * memberExpr = isThisMemberExpr( firstParam, thisParam ) ) {
1078 // if first parameter is a member expression on the this parameter,
1079 // then remove the member from unhandled set.
1080 if ( isThisExpression( memberExpr->get_aggregate(), thisParam ) ) {
1081 unhandled.erase( memberExpr->get_member() );
1082 }
1083 }
1084 }
1085 }
1086
1087 void GenStructMemberCalls::previsit( MemberExpr * memberExpr ) {
1088 if ( ! checkWarnings( function ) || ! isCtor ) {
1089 visit_children = false;
1090 return;
1091 }
1092
1093 if ( isThisExpression( memberExpr->get_aggregate(), thisParam ) ) {
1094 if ( unhandled.count( memberExpr->get_member() ) ) {
1095 // emit a warning because a member was used before it was constructed
1096 usedUninit.insert( { memberExpr->get_member(), memberExpr->location } );
1097 }
1098 }
1099 }
1100
1101 template< typename Visitor, typename... Params >
1102 void error( Visitor & v, CodeLocation loc, const Params &... params ) {
1103 SemanticError err( toString( params... ) );
1104 err.set_location( loc );
1105 v.errors.append( err );
1106 }
1107
1108 template< typename... Params >
1109 void GenStructMemberCalls::emit( CodeLocation loc, const Params &... params ) {
1110 // toggle warnings vs. errors here.
1111 // warn( params... );
1112 error( *this, loc, params... );
1113 }
1114
1115 DeclarationWithType * MutatingResolver::mutate( ObjectDecl *objectDecl ) {
1116 // add object to the indexer assumes that there will be no name collisions
1117 // in generated code. If this changes, add mutate methods for entities with
1118 // scope and call {enter,leave}Scope explicitly.
1119 indexer.addId( objectDecl );
1120 return objectDecl;
1121 }
1122
1123 Expression* MutatingResolver::mutate( UntypedExpr *untypedExpr ) {
1124 return strict_dynamic_cast< ApplicationExpr * >( ResolvExpr::findVoidExpression( untypedExpr, indexer ) );
1125 }
1126
1127 Expression * FixCtorExprs::postmutate( ConstructorExpr * ctorExpr ) {
1128 static UniqueName tempNamer( "_tmp_ctor_expr" );
1129 // xxx - is the size check necessary?
1130 assert( ctorExpr->has_result() && ctorExpr->get_result()->size() == 1 );
1131
1132 // xxx - ideally we would reuse the temporary generated from the copy constructor passes from within firstArg if it exists and not generate a temporary if it's unnecessary.
1133 ObjectDecl * tmp = ObjectDecl::newObject( tempNamer.newName(), ctorExpr->get_result()->clone(), nullptr );
1134 declsToAddBefore.push_back( tmp );
1135
1136 // xxx - this can be TupleAssignExpr now. Need to properly handle this case.
1137 ApplicationExpr * callExpr = strict_dynamic_cast< ApplicationExpr * > ( ctorExpr->get_callExpr() );
1138 TypeSubstitution * env = ctorExpr->get_env();
1139 ctorExpr->set_callExpr( nullptr );
1140 ctorExpr->set_env( nullptr );
1141 delete ctorExpr;
1142
1143 // build assignment and replace constructor's first argument with new temporary
1144 Expression *& firstArg = callExpr->get_args().front();
1145 Expression * assign = new UntypedExpr( new NameExpr( "?=?" ), { new AddressExpr( new VariableExpr( tmp ) ), new AddressExpr( firstArg ) } );
1146 firstArg = new VariableExpr( tmp );
1147
1148 // resolve assignment and dispose of new env
1149 Expression * resolvedAssign = ResolvExpr::findVoidExpression( assign, indexer );
1150 delete resolvedAssign->env;
1151 resolvedAssign->env = nullptr;
1152 delete assign;
1153
1154 // for constructor expr:
1155 // T x;
1156 // x{};
1157 // results in:
1158 // T x;
1159 // T & tmp;
1160 // &tmp = &x, ?{}(tmp), tmp
1161 CommaExpr * commaExpr = new CommaExpr( resolvedAssign, new CommaExpr( callExpr, new VariableExpr( tmp ) ) );
1162 commaExpr->set_env( env );
1163 return commaExpr;
1164 }
1165 } // namespace
1166} // namespace InitTweak
1167
1168// Local Variables: //
1169// tab-width: 4 //
1170// mode: c++ //
1171// compile-command: "make install" //
1172// End: //
Note: See TracBrowser for help on using the repository browser.