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