source: src/InitTweak/FixInit.cc@ fc56cdbf

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 with_gc
Last change on this file since fc56cdbf was 5ccb10d, checked in by Rob Schluntz <rschlunt@…>, 8 years ago

Set reference size to base size, clean up debug code, remove more old-style NULLs from prelude

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