[51587aa] | 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 | // |
---|
[c92bdcc] | 7 | // GenInit.cpp -- Generate initializers, and other stuff. |
---|
[51587aa] | 8 | // |
---|
[cf16f94] | 9 | // Author : Rob Schluntz |
---|
[51587aa] | 10 | // Created On : Mon May 18 07:44:20 2015 |
---|
[a36eb2d] | 11 | // Last Modified By : Andrew Beach |
---|
[148ba7d] | 12 | // Last Modified On : Mon Oct 25 13:53:00 2021 |
---|
| 13 | // Update Count : 186 |
---|
[51587aa] | 14 | // |
---|
[c92bdcc] | 15 | #include "GenInit.hpp" |
---|
[8ca3a72] | 16 | |
---|
[2bfc6b2] | 17 | #include <stddef.h> // for NULL |
---|
| 18 | #include <algorithm> // for any_of |
---|
| 19 | #include <cassert> // for assert, strict_dynamic_cast, assertf |
---|
[b8524ca] | 20 | #include <deque> |
---|
[2bfc6b2] | 21 | #include <iterator> // for back_inserter, inserter, back_inse... |
---|
| 22 | #include <list> // for _List_iterator, list |
---|
[8ca3a72] | 23 | |
---|
[b8524ca] | 24 | #include "AST/Decl.hpp" |
---|
| 25 | #include "AST/Init.hpp" |
---|
[a36eb2d] | 26 | #include "AST/Pass.hpp" |
---|
[b8524ca] | 27 | #include "AST/Node.hpp" |
---|
| 28 | #include "AST/Stmt.hpp" |
---|
[b2ea0cd] | 29 | #include "CompilationState.hpp" |
---|
[c92bdcc] | 30 | #include "CodeGen/OperatorTable.hpp" |
---|
| 31 | #include "Common/SemanticError.hpp" // for SemanticError |
---|
[9feb34b] | 32 | #include "Common/ToString.hpp" // for toCString |
---|
[c92bdcc] | 33 | #include "Common/UniqueName.hpp" // for UniqueName |
---|
| 34 | #include "GenPoly/GenPoly.hpp" // for getFunctionType, isPolyType |
---|
| 35 | #include "GenPoly/ScopedSet.hpp" // for ScopedSet, ScopedSet<>::const_iter... |
---|
| 36 | #include "InitTweak.hpp" // for isConstExpr, InitExpander, checkIn... |
---|
| 37 | #include "ResolvExpr/Resolver.hpp" |
---|
[fb4dc28] | 38 | #include "SymTab/GenImplicitCall.hpp" // for genImplicitCall |
---|
[c92bdcc] | 39 | #include "SymTab/Mangler.hpp" // for Mangler |
---|
| 40 | #include "Tuples/Tuples.hpp" // for maybeImpure |
---|
[42e2ad7] | 41 | |
---|
| 42 | namespace InitTweak { |
---|
[09867ec] | 43 | |
---|
[a36eb2d] | 44 | namespace { |
---|
| 45 | |
---|
[f02f546] | 46 | // Outer pass finds declarations, for their type could wrap a type that needs hoisting |
---|
[0bd3faf] | 47 | struct HoistArrayDimension_NoResolve final : |
---|
[a36eb2d] | 48 | public ast::WithDeclsToAdd<>, public ast::WithShortCircuiting, |
---|
[c600df1] | 49 | public ast::WithGuards, public ast::WithConstTranslationUnit, |
---|
[0bd3faf] | 50 | public ast::WithVisitorRef<HoistArrayDimension_NoResolve>, |
---|
[f02f546] | 51 | public ast::WithSymbolTableX<ast::SymbolTable::ErrorDetection::IgnoreErrors> { |
---|
| 52 | |
---|
| 53 | // Inner pass looks within a type, for a part that depends on an expression |
---|
| 54 | struct HoistDimsFromTypes final : |
---|
| 55 | public ast::WithShortCircuiting, public ast::WithGuards { |
---|
| 56 | |
---|
[0bd3faf] | 57 | HoistArrayDimension_NoResolve * outer; |
---|
| 58 | HoistDimsFromTypes( HoistArrayDimension_NoResolve * outer ) : outer(outer) {} |
---|
[f02f546] | 59 | |
---|
| 60 | // Only intended for visiting through types. |
---|
| 61 | // Tolerate, and short-circuit at, the dimension expression of an array type. |
---|
| 62 | // (We'll operate on the dimension expression of an array type directly |
---|
| 63 | // from the parent type, not by visiting through it) |
---|
| 64 | // Look inside type exprs. |
---|
| 65 | void previsit( const ast::Node * ) { |
---|
| 66 | assert( false && "unsupported node type" ); |
---|
| 67 | }; |
---|
| 68 | const ast::Expr * allowedExpr = nullptr; |
---|
| 69 | void previsit( const ast::Type * ) { |
---|
| 70 | GuardValue( allowedExpr ) = nullptr; |
---|
| 71 | } |
---|
| 72 | void previsit( const ast::ArrayType * t ) { |
---|
| 73 | GuardValue( allowedExpr ) = t->dimension.get(); |
---|
| 74 | } |
---|
| 75 | void previsit( const ast::PointerType * t ) { |
---|
| 76 | GuardValue( allowedExpr ) = t->dimension.get(); |
---|
| 77 | } |
---|
| 78 | void previsit( const ast::TypeofType * t ) { |
---|
| 79 | GuardValue( allowedExpr ) = t->expr.get(); |
---|
| 80 | } |
---|
| 81 | void previsit( const ast::Expr * e ) { |
---|
| 82 | assert( e == allowedExpr && |
---|
| 83 | "only expecting to visit exprs that are dimension exprs or typeof(-) inner exprs" ); |
---|
[a36eb2d] | 84 | |
---|
[f02f546] | 85 | // Skip the tolerated expressions |
---|
| 86 | visit_children = false; |
---|
| 87 | } |
---|
| 88 | void previsit( const ast::TypeExpr * ) {} |
---|
| 89 | |
---|
| 90 | const ast::Type * postvisit( |
---|
| 91 | const ast::ArrayType * arrayType ) { |
---|
| 92 | static UniqueName dimensionName( "_array_dim" ); |
---|
| 93 | |
---|
| 94 | if ( nullptr == arrayType->dimension ) { // if no dimension is given, don't presume to invent one |
---|
| 95 | return arrayType; |
---|
| 96 | } |
---|
| 97 | |
---|
| 98 | // find size_t; use it as the type for a dim expr |
---|
| 99 | ast::ptr<ast::Type> dimType = outer->transUnit().global.sizeType; |
---|
| 100 | assert( dimType ); |
---|
| 101 | add_qualifiers( dimType, ast::CV::Qualifiers( ast::CV::Const ) ); |
---|
| 102 | |
---|
| 103 | // Special-case handling: leave the user's dimension expression alone |
---|
| 104 | // - requires the user to have followed a careful convention |
---|
| 105 | // - may apply to extremely simple applications, but only as windfall |
---|
| 106 | // - users of advanced applications will be following the convention on purpose |
---|
| 107 | // - CFA maintainers must protect the criteria against leaving too much alone |
---|
| 108 | |
---|
| 109 | // Actual leave-alone cases following are conservative approximations of "cannot vary" |
---|
| 110 | |
---|
| 111 | // Leave alone: literals and enum constants |
---|
| 112 | if ( dynamic_cast< const ast::ConstantExpr * >( arrayType->dimension.get() ) ) { |
---|
| 113 | return arrayType; |
---|
| 114 | } |
---|
| 115 | |
---|
| 116 | // Leave alone: direct use of an object declared to be const |
---|
| 117 | const ast::NameExpr * dimn = dynamic_cast< const ast::NameExpr * >( arrayType->dimension.get() ); |
---|
| 118 | if ( dimn ) { |
---|
| 119 | std::vector<ast::SymbolTable::IdData> dimnDefs = outer->symtab.lookupId( dimn->name ); |
---|
| 120 | if ( dimnDefs.size() == 1 ) { |
---|
| 121 | const ast::DeclWithType * dimnDef = dimnDefs[0].id.get(); |
---|
| 122 | assert( dimnDef && "symbol table binds a name to nothing" ); |
---|
| 123 | const ast::ObjectDecl * dimOb = dynamic_cast< const ast::ObjectDecl * >( dimnDef ); |
---|
| 124 | if( dimOb ) { |
---|
| 125 | const ast::Type * dimTy = dimOb->type.get(); |
---|
| 126 | assert( dimTy && "object declaration bearing no type" ); |
---|
| 127 | // must not hoist some: size_t |
---|
| 128 | // must hoist all: pointers and references |
---|
| 129 | // the analysis is conservative; BasicType is a simple approximation |
---|
| 130 | if ( dynamic_cast< const ast::BasicType * >( dimTy ) || |
---|
| 131 | dynamic_cast< const ast::SueInstType<ast::EnumDecl> * >( dimTy ) ) { |
---|
| 132 | if ( dimTy->is_const() ) { |
---|
| 133 | // The dimension is certainly re-evaluable, giving the same answer each time. |
---|
| 134 | // Our user might be hoping to write the array type in multiple places, having them unify. |
---|
| 135 | // Leave the type alone. |
---|
| 136 | |
---|
| 137 | // We believe the new criterion leaves less alone than the old criterion. |
---|
| 138 | // Thus, the old criterion should have left the current case alone. |
---|
| 139 | // Catch cases that weren't thought through. |
---|
| 140 | assert( !Tuples::maybeImpure( arrayType->dimension ) ); |
---|
| 141 | |
---|
| 142 | return arrayType; |
---|
| 143 | } |
---|
| 144 | }; |
---|
| 145 | } |
---|
| 146 | } |
---|
| 147 | } |
---|
| 148 | |
---|
| 149 | // Leave alone: any sizeof expression (answer cannot vary during current lexical scope) |
---|
| 150 | const ast::SizeofExpr * sz = dynamic_cast< const ast::SizeofExpr * >( arrayType->dimension.get() ); |
---|
| 151 | if ( sz ) { |
---|
| 152 | return arrayType; |
---|
| 153 | } |
---|
| 154 | |
---|
| 155 | // General-case handling: change the array-type's dim expr (hoist the user-given content out of the type) |
---|
| 156 | // - always safe |
---|
| 157 | // - user-unnoticeable in common applications (benign noise in -CFA output) |
---|
| 158 | // - may annoy a responsible user of advanced applications (but they can work around) |
---|
| 159 | // - protects against misusing advanced features |
---|
| 160 | // |
---|
| 161 | // The hoist, by example, is: |
---|
| 162 | // FROM USER: float a[ rand() ]; |
---|
| 163 | // TO GCC: const size_t __len_of_a = rand(); float a[ __len_of_a ]; |
---|
| 164 | |
---|
| 165 | ast::ObjectDecl * arrayDimension = new ast::ObjectDecl( |
---|
| 166 | arrayType->dimension->location, |
---|
| 167 | dimensionName.newName(), |
---|
| 168 | dimType, |
---|
| 169 | new ast::SingleInit( |
---|
| 170 | arrayType->dimension->location, |
---|
| 171 | arrayType->dimension |
---|
| 172 | ) |
---|
| 173 | ); |
---|
| 174 | |
---|
| 175 | ast::ArrayType * mutType = ast::mutate( arrayType ); |
---|
| 176 | mutType->dimension = new ast::VariableExpr( |
---|
| 177 | arrayDimension->location, arrayDimension ); |
---|
| 178 | outer->declsToAddBefore.push_back( arrayDimension ); |
---|
| 179 | |
---|
| 180 | return mutType; |
---|
| 181 | } // postvisit( const ast::ArrayType * ) |
---|
| 182 | }; // struct HoistDimsFromTypes |
---|
[a36eb2d] | 183 | |
---|
| 184 | ast::Storage::Classes storageClasses; |
---|
[f02f546] | 185 | void previsit( |
---|
| 186 | const ast::ObjectDecl * decl ) { |
---|
| 187 | GuardValue( storageClasses ) = decl->storage; |
---|
[a36eb2d] | 188 | } |
---|
| 189 | |
---|
[f02f546] | 190 | const ast::DeclWithType * postvisit( |
---|
| 191 | const ast::ObjectDecl * objectDecl ) { |
---|
[a36eb2d] | 192 | |
---|
[f02f546] | 193 | if ( !isInFunction() || storageClasses.is_static ) { |
---|
| 194 | return objectDecl; |
---|
[a36eb2d] | 195 | } |
---|
| 196 | |
---|
[f02f546] | 197 | const ast::Type * mid = objectDecl->type; |
---|
[a36eb2d] | 198 | |
---|
[f02f546] | 199 | ast::Pass<HoistDimsFromTypes> hoist{this}; |
---|
| 200 | const ast::Type * result = mid->accept( hoist ); |
---|
[a36eb2d] | 201 | |
---|
[f02f546] | 202 | return mutate_field( objectDecl, &ast::ObjectDecl::type, result ); |
---|
[a36eb2d] | 203 | } |
---|
[f02f546] | 204 | }; |
---|
| 205 | |
---|
[0bd3faf] | 206 | struct ReturnFixer final : |
---|
[fc134a48] | 207 | public ast::WithStmtsToAdd<>, ast::WithGuards, ast::WithShortCircuiting { |
---|
[a36eb2d] | 208 | void previsit( const ast::FunctionDecl * decl ); |
---|
| 209 | const ast::ReturnStmt * previsit( const ast::ReturnStmt * stmt ); |
---|
| 210 | private: |
---|
| 211 | const ast::FunctionDecl * funcDecl = nullptr; |
---|
| 212 | }; |
---|
| 213 | |
---|
[0bd3faf] | 214 | void ReturnFixer::previsit( const ast::FunctionDecl * decl ) { |
---|
[fc134a48] | 215 | if (decl->linkage == ast::Linkage::Intrinsic) visit_children = false; |
---|
[148ba7d] | 216 | GuardValue( funcDecl ) = decl; |
---|
[a36eb2d] | 217 | } |
---|
| 218 | |
---|
[0bd3faf] | 219 | const ast::ReturnStmt * ReturnFixer::previsit( |
---|
[a36eb2d] | 220 | const ast::ReturnStmt * stmt ) { |
---|
| 221 | auto & returns = funcDecl->returns; |
---|
| 222 | assert( returns.size() < 2 ); |
---|
| 223 | // Hands off if the function returns a reference. |
---|
| 224 | // Don't allocate a temporary if the address is returned. |
---|
| 225 | if ( stmt->expr && 1 == returns.size() ) { |
---|
| 226 | ast::ptr<ast::DeclWithType> retDecl = returns.front(); |
---|
| 227 | if ( isConstructable( retDecl->get_type() ) ) { |
---|
| 228 | // Explicitly construct the return value using the return |
---|
| 229 | // expression and the retVal object. |
---|
| 230 | assertf( "" != retDecl->name, |
---|
| 231 | "Function %s has unnamed return value.\n", |
---|
| 232 | funcDecl->name.c_str() ); |
---|
| 233 | |
---|
| 234 | auto retVal = retDecl.strict_as<ast::ObjectDecl>(); |
---|
| 235 | if ( auto varExpr = stmt->expr.as<ast::VariableExpr>() ) { |
---|
| 236 | // Check if the return statement is already set up. |
---|
| 237 | if ( varExpr->var == retVal ) return stmt; |
---|
| 238 | } |
---|
[4e2f1b2] | 239 | const ast::Stmt * ctorStmt = genCtorDtor( |
---|
[a36eb2d] | 240 | retVal->location, "?{}", retVal, stmt->expr ); |
---|
| 241 | assertf( ctorStmt, |
---|
[4ec9513] | 242 | "ReturnFixer: genCtorDtor returned nullptr: %s / %s", |
---|
[a36eb2d] | 243 | toString( retVal ).c_str(), |
---|
| 244 | toString( stmt->expr ).c_str() ); |
---|
[4ec9513] | 245 | stmtsToAddBefore.push_back( ctorStmt ); |
---|
[a36eb2d] | 246 | |
---|
| 247 | // Return the retVal object. |
---|
| 248 | ast::ReturnStmt * mutStmt = ast::mutate( stmt ); |
---|
| 249 | mutStmt->expr = new ast::VariableExpr( |
---|
| 250 | stmt->location, retDecl ); |
---|
| 251 | return mutStmt; |
---|
| 252 | } |
---|
| 253 | } |
---|
| 254 | return stmt; |
---|
| 255 | } |
---|
| 256 | |
---|
| 257 | } // namespace |
---|
| 258 | |
---|
[8984003] | 259 | void genInit( ast::TranslationUnit & transUnit ) { |
---|
| 260 | ast::Pass<HoistArrayDimension_NoResolve>::run( transUnit ); |
---|
| 261 | ast::Pass<ReturnFixer>::run( transUnit ); |
---|
| 262 | } |
---|
| 263 | |
---|
| 264 | void fixReturnStatements( ast::TranslationUnit & transUnit ) { |
---|
| 265 | ast::Pass<ReturnFixer>::run( transUnit ); |
---|
| 266 | } |
---|
| 267 | |
---|
| 268 | bool ManagedTypes::isManaged( const ast::Type * type ) const { |
---|
| 269 | // references are never constructed |
---|
| 270 | if ( dynamic_cast< const ast::ReferenceType * >( type ) ) return false; |
---|
| 271 | if ( auto tupleType = dynamic_cast< const ast::TupleType * > ( type ) ) { |
---|
| 272 | // tuple is also managed if any of its components are managed |
---|
| 273 | for (auto & component : tupleType->types) { |
---|
| 274 | if (isManaged(component)) return true; |
---|
[16ba4a6f] | 275 | } |
---|
| 276 | } |
---|
[8984003] | 277 | // need to clear and reset qualifiers when determining if a type is managed |
---|
| 278 | auto tmp = shallowCopy(type); |
---|
| 279 | tmp->qualifiers = {}; |
---|
| 280 | // delete tmp at return |
---|
| 281 | ast::ptr<ast::Type> guard = tmp; |
---|
| 282 | // a type is managed if it appears in the map of known managed types, or if it contains any polymorphism (is a type variable or generic type containing a type variable) |
---|
| 283 | return managedTypes.find( Mangle::mangle( tmp, {Mangle::NoOverrideable | Mangle::NoGenericParams | Mangle::Type} ) ) != managedTypes.end() || GenPoly::isPolyType( tmp ); |
---|
| 284 | } |
---|
| 285 | |
---|
| 286 | bool ManagedTypes::isManaged( const ast::ObjectDecl * objDecl ) const { |
---|
| 287 | const ast::Type * type = objDecl->type; |
---|
| 288 | while ( auto at = dynamic_cast< const ast::ArrayType * >( type ) ) { |
---|
| 289 | // must always construct VLAs with an initializer, since this is an error in C |
---|
| 290 | if ( at->isVarLen && objDecl->init ) return true; |
---|
| 291 | type = at->base; |
---|
[16ba4a6f] | 292 | } |
---|
[8984003] | 293 | return isManaged( type ); |
---|
| 294 | } |
---|
| 295 | |
---|
| 296 | void ManagedTypes::handleDWT( const ast::DeclWithType * dwt ) { |
---|
| 297 | // if this function is a user-defined constructor or destructor, mark down the type as "managed" |
---|
| 298 | if ( ! dwt->linkage.is_overrideable && CodeGen::isCtorDtor( dwt->name ) ) { |
---|
| 299 | auto & params = GenPoly::getFunctionType( dwt->get_type())->params; |
---|
| 300 | assert( ! params.empty() ); |
---|
| 301 | // Type * type = InitTweak::getPointerBase( params.front() ); |
---|
| 302 | // assert( type ); |
---|
| 303 | managedTypes.insert( Mangle::mangle( params.front(), {Mangle::NoOverrideable | Mangle::NoGenericParams | Mangle::Type} ) ); |
---|
[16ba4a6f] | 304 | } |
---|
[8984003] | 305 | } |
---|
| 306 | |
---|
| 307 | void ManagedTypes::handleStruct( const ast::StructDecl * aggregateDecl ) { |
---|
| 308 | // don't construct members, but need to take note if there is a managed member, |
---|
| 309 | // because that means that this type is also managed |
---|
| 310 | for ( auto & member : aggregateDecl->members ) { |
---|
| 311 | if ( auto field = member.as<ast::ObjectDecl>() ) { |
---|
| 312 | if ( isManaged( field ) ) { |
---|
| 313 | // generic parameters should not play a role in determining whether a generic type is constructed - construct all generic types, so that |
---|
| 314 | // polymorphic constructors make generic types managed types |
---|
| 315 | ast::StructInstType inst( aggregateDecl ); |
---|
| 316 | managedTypes.insert( Mangle::mangle( &inst, {Mangle::NoOverrideable | Mangle::NoGenericParams | Mangle::Type} ) ); |
---|
| 317 | break; |
---|
[16ba4a6f] | 318 | } |
---|
| 319 | } |
---|
| 320 | } |
---|
[8984003] | 321 | } |
---|
[16ba4a6f] | 322 | |
---|
[8984003] | 323 | void ManagedTypes::beginScope() { managedTypes.beginScope(); } |
---|
| 324 | void ManagedTypes::endScope() { managedTypes.endScope(); } |
---|
[16ba4a6f] | 325 | |
---|
[4e2f1b2] | 326 | const ast::Stmt * genCtorDtor( const CodeLocation & loc, const std::string & fname, const ast::ObjectDecl * objDecl, const ast::Expr * arg ) { |
---|
[8984003] | 327 | assertf(objDecl, "genCtorDtor passed null objDecl"); |
---|
| 328 | InitExpander srcParam(arg); |
---|
| 329 | return SymTab::genImplicitCall(srcParam, new ast::VariableExpr(loc, objDecl), loc, fname, objDecl); |
---|
| 330 | } |
---|
[092528b] | 331 | |
---|
[b8524ca] | 332 | ast::ConstructorInit * genCtorInit( const CodeLocation & loc, const ast::ObjectDecl * objDecl ) { |
---|
[5f225f5] | 333 | // Call genImplicitCall to generate calls to ctor/dtor for each constructable object. |
---|
[0bd3faf] | 334 | InitExpander srcParam{ objDecl->init }, nullParam{ (const ast::Init *)nullptr }; |
---|
[16ba4a6f] | 335 | ast::ptr< ast::Expr > dstParam = new ast::VariableExpr(loc, objDecl); |
---|
[c19edd1] | 336 | |
---|
| 337 | ast::ptr< ast::Stmt > ctor = SymTab::genImplicitCall( |
---|
[16ba4a6f] | 338 | srcParam, dstParam, loc, "?{}", objDecl ); |
---|
[c19edd1] | 339 | ast::ptr< ast::Stmt > dtor = SymTab::genImplicitCall( |
---|
| 340 | nullParam, dstParam, loc, "^?{}", objDecl, |
---|
[b8524ca] | 341 | SymTab::LoopBackward ); |
---|
[c19edd1] | 342 | |
---|
[b8524ca] | 343 | // check that either both ctor and dtor are present, or neither |
---|
| 344 | assert( (bool)ctor == (bool)dtor ); |
---|
| 345 | |
---|
| 346 | if ( ctor ) { |
---|
[c19edd1] | 347 | // need to remember init expression, in case no ctors exist. If ctor does exist, want to |
---|
[b8524ca] | 348 | // use ctor expression instead of init. |
---|
[c19edd1] | 349 | ctor.strict_as< ast::ImplicitCtorDtorStmt >(); |
---|
[b8524ca] | 350 | dtor.strict_as< ast::ImplicitCtorDtorStmt >(); |
---|
| 351 | |
---|
| 352 | return new ast::ConstructorInit{ loc, ctor, dtor, objDecl->init }; |
---|
| 353 | } |
---|
| 354 | |
---|
[234b1cb] | 355 | return nullptr; |
---|
| 356 | } |
---|
| 357 | |
---|
[42e2ad7] | 358 | } // namespace InitTweak |
---|
| 359 | |
---|
[51587aa] | 360 | // Local Variables: // |
---|
| 361 | // tab-width: 4 // |
---|
| 362 | // mode: c++ // |
---|
| 363 | // compile-command: "make install" // |
---|
| 364 | // End: // |
---|