source: src/InitTweak/FixInit.cpp@ 0497b6ba

Last change on this file since 0497b6ba was ed96731, checked in by Andrew Beach <ajbeach@…>, 10 months ago

With{Stmts,Decls}ToAdd how has an -X version like WithSymbolTableX. Although these -X versions might be useful can could possibly be removed in the future. (This is a therapy commit.)

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