source: src/InitTweak/FixInit.cc@ 7b10ea9

ADT arm-eh ast-experimental cleanup-dtors enum forall-pointer-decay jacob/cs343-translation jenkins-sandbox new-ast new-ast-unique-expr pthread-emulation qualifiedEnum
Last change on this file since 7b10ea9 was bcc0946, checked in by Rob Schluntz <rschlunt@…>, 7 years ago

Minor code cleanup

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