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