source: src/InitTweak/FixInit.cc@ ec42ff2e

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

Add SplitExpressions pass to wrap top-level expressions in CompoundStmts

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