source: src/Tuples/TupleExpansion.cc@ 6fa409e

new-env
Last change on this file since 6fa409e was cdc4d43, checked in by Aaron Moss <a3moss@…>, 7 years ago

Fix leftover delete from last merge

  • Property mode set to 100644
File size: 14.6 KB
RevLine 
[6eb8948]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// TupleAssignment.cc --
8//
9// Author : Rodolfo G. Esteves
10// Created On : Mon May 18 07:44:20 2015
11// Last Modified By : Peter A. Buhr
[d56e5bc]12// Last Modified On : Wed Jun 21 17:35:04 2017
13// Update Count : 19
[6eb8948]14//
15
[03321e4]16#include <stddef.h> // for size_t
17#include <cassert> // for assert
18#include <list> // for list
19
20#include "Common/PassVisitor.h" // for PassVisitor, WithDeclsToAdd, WithGu...
21#include "Common/ScopedMap.h" // for ScopedMap
22#include "Common/utility.h" // for CodeLocation
23#include "InitTweak/InitTweak.h" // for getFunction
24#include "Parser/LinkageSpec.h" // for Spec, C, Intrinsic
25#include "SynTree/Constant.h" // for Constant
26#include "SynTree/Declaration.h" // for StructDecl, DeclarationWithType
27#include "SynTree/Expression.h" // for UntypedMemberExpr, Expression, Uniq...
28#include "SynTree/Label.h" // for operator==, Label
29#include "SynTree/Mutator.h" // for Mutator
30#include "SynTree/Type.h" // for Type, Type::Qualifiers, TupleType
31#include "SynTree/Visitor.h" // for Visitor
[aee472e]32#include "Tuples.h"
[03321e4]33
34class CompoundStmt;
35class TypeSubstitution;
[6eb8948]36
37namespace Tuples {
[3c13c03]38 namespace {
[f240484]39 struct MemberTupleExpander final : public WithShortCircuiting, public WithVisitorRef<MemberTupleExpander> {
40 void premutate( UntypedMemberExpr * ) { visit_children = false; }
41 Expression * postmutate( UntypedMemberExpr * memberExpr );
[bf32bb8]42 };
43
[9f10c4b8]44 struct UniqueExprExpander final : public WithDeclsToAdd {
45 Expression * postmutate( UniqueExpr * unqExpr );
[141b786]46
47 std::map< int, Expression * > decls; // not vector, because order added may not be increasing order
[3c13c03]48 };
49
[9f10c4b8]50 struct TupleAssignExpander {
51 Expression * postmutate( TupleAssignExpr * tupleExpr );
[3c13c03]52 };
53
[c92c09c]54 struct TupleTypeReplacer : public WithDeclsToAdd, public WithGuards, public WithTypeSubstitution {
55 Type * postmutate( TupleType * tupleType );
[3c13c03]56
[c92c09c]57 void premutate( CompoundStmt * ) {
58 GuardScope( typeMap );
[3c13c03]59 }
60 private:
[e6512c8]61 ScopedMap< int, StructDecl * > typeMap;
[3c13c03]62 };
63
[c93bc28]64 struct TupleIndexExpander {
[ab904dc]65 Expression * postmutate( TupleIndexExpr * tupleExpr );
[3c13c03]66 };
67
[9f10c4b8]68 struct TupleExprExpander final {
69 Expression * postmutate( TupleExpr * tupleExpr );
[3c13c03]70 };
71 }
[f006f01]72
[bf32bb8]73 void expandMemberTuples( std::list< Declaration * > & translationUnit ) {
[f240484]74 PassVisitor<MemberTupleExpander> expander;
[bf32bb8]75 mutateAll( translationUnit, expander );
76 }
77
[aefcc3b]78 void expandUniqueExpr( std::list< Declaration * > & translationUnit ) {
[9f10c4b8]79 PassVisitor<UniqueExprExpander> unqExpander;
80 mutateAll( translationUnit, unqExpander );
[aefcc3b]81 }
[3c13c03]82
[aefcc3b]83 void expandTuples( std::list< Declaration * > & translationUnit ) {
[9f10c4b8]84 PassVisitor<TupleAssignExpander> assnExpander;
[3c13c03]85 mutateAll( translationUnit, assnExpander );
[f006f01]86
[c92c09c]87 PassVisitor<TupleTypeReplacer> replacer;
88 mutateAll( translationUnit, replacer );
[3c13c03]89
[ab904dc]90 PassVisitor<TupleIndexExpander> idxExpander;
[3c13c03]91 mutateAll( translationUnit, idxExpander );
92
[9f10c4b8]93 PassVisitor<TupleExprExpander> exprExpander;
[3c13c03]94 mutateAll( translationUnit, exprExpander );
95 }
96
[bf32bb8]97 namespace {
98 /// given a expression representing the member and an expression representing the aggregate,
99 /// reconstructs a flattened UntypedMemberExpr with the right precedence
[64ac636]100 Expression * reconstructMemberExpr( Expression * member, Expression * aggr, CodeLocation & loc ) {
[bf32bb8]101 if ( UntypedMemberExpr * memberExpr = dynamic_cast< UntypedMemberExpr * >( member ) ) {
102 // construct a new UntypedMemberExpr with the correct structure , and recursively
103 // expand that member expression.
[f240484]104 PassVisitor<MemberTupleExpander> expander;
105 UntypedMemberExpr * inner = new UntypedMemberExpr( memberExpr->aggregate, aggr->clone() );
106 UntypedMemberExpr * newMemberExpr = new UntypedMemberExpr( memberExpr->member, inner );
[64ac636]107 inner->location = newMemberExpr->location = loc;
[bf32bb8]108 return newMemberExpr->acceptMutator( expander );
109 } else {
110 // not a member expression, so there is nothing to do but attach and return
[64ac636]111 UntypedMemberExpr * newMemberExpr = new UntypedMemberExpr( member, aggr->clone() );
112 newMemberExpr->location = loc;
113 return newMemberExpr;
[bf32bb8]114 }
115 }
116 }
117
[f240484]118 Expression * MemberTupleExpander::postmutate( UntypedMemberExpr * memberExpr ) {
119 if ( UntypedTupleExpr * tupleExpr = dynamic_cast< UntypedTupleExpr * > ( memberExpr->member ) ) {
120 Expression * aggr = memberExpr->aggregate->clone()->acceptMutator( *visitor );
[141b786]121 // aggregate expressions which might be impure must be wrapped in unique expressions
[aee472e]122 if ( Tuples::maybeImpureIgnoreUnique( memberExpr->aggregate ) ) aggr = new UniqueExpr( aggr );
[f240484]123 for ( Expression *& expr : tupleExpr->exprs ) {
[64ac636]124 expr = reconstructMemberExpr( expr, aggr, memberExpr->location );
125 expr->location = memberExpr->location;
[bf32bb8]126 }
[64ac636]127 tupleExpr->location = memberExpr->location;
[bf32bb8]128 return tupleExpr;
129 } else {
[f0121d7]130 // there may be a tuple expr buried in the aggregate
131 // xxx - this is a memory leak
[f240484]132 UntypedMemberExpr * newMemberExpr = new UntypedMemberExpr( memberExpr->member->clone(), memberExpr->aggregate->acceptMutator( *visitor ) );
[64ac636]133 newMemberExpr->location = memberExpr->location;
134 return newMemberExpr;
[bf32bb8]135 }
136 }
137
[9f10c4b8]138 Expression * UniqueExprExpander::postmutate( UniqueExpr * unqExpr ) {
[141b786]139 const int id = unqExpr->get_id();
140
141 // on first time visiting a unique expr with a particular ID, generate the expression that replaces all UniqueExprs with that ID,
142 // and lookup on subsequent hits. This ensures that all unique exprs with the same ID reference the same variable.
143 if ( ! decls.count( id ) ) {
144 Expression * assignUnq;
145 Expression * var = unqExpr->get_var();
146 if ( unqExpr->get_object() ) {
147 // an object was generated to represent this unique expression -- it should be added to the list of declarations now
[9f10c4b8]148 declsToAddBefore.push_back( unqExpr->get_object() );
[141b786]149 unqExpr->set_object( nullptr );
150 // steal the expr from the unqExpr
151 assignUnq = UntypedExpr::createAssign( unqExpr->get_var()->clone(), unqExpr->get_expr() );
152 unqExpr->set_expr( nullptr );
153 } else {
154 // steal the already generated assignment to var from the unqExpr - this has been generated by FixInit
155 Expression * expr = unqExpr->get_expr();
[e3e16bc]156 CommaExpr * commaExpr = strict_dynamic_cast< CommaExpr * >( expr );
[141b786]157 assignUnq = commaExpr->get_arg1();
158 commaExpr->set_arg1( nullptr );
159 }
[d56e5bc]160 ObjectDecl * finished = new ObjectDecl( toString( "_unq", id, "_finished_" ), Type::StorageClasses(), LinkageSpec::Cforall, nullptr, new BasicType( Type::Qualifiers(), BasicType::Bool ),
[579263a]161 new SingleInit( new ConstantExpr( Constant::from_int( 0 ) ) ) );
[9f10c4b8]162 declsToAddBefore.push_back( finished );
[141b786]163 // (finished ? _unq_expr_N : (_unq_expr_N = <unqExpr->get_expr()>, finished = 1, _unq_expr_N))
164 // This pattern ensures that each unique expression is evaluated once, regardless of evaluation order of the generated C code.
[d56e5bc]165 Expression * assignFinished = UntypedExpr::createAssign( new VariableExpr(finished), new ConstantExpr( Constant::from_int( 1 ) ) );
[141b786]166 ConditionalExpr * condExpr = new ConditionalExpr( new VariableExpr( finished ), var->clone(),
167 new CommaExpr( new CommaExpr( assignUnq, assignFinished ), var->clone() ) );
168 condExpr->set_result( var->get_result()->clone() );
[d5556a3]169 condExpr->set_env( maybeClone( unqExpr->get_env() ) );
[141b786]170 decls[id] = condExpr;
[3c13c03]171 }
[141b786]172 return decls[id]->clone();
[6eb8948]173 }
174
[9f10c4b8]175 Expression * TupleAssignExpander::postmutate( TupleAssignExpr * assnExpr ) {
[d5556a3]176 StmtExpr * ret = assnExpr->get_stmtExpr();
177 assnExpr->set_stmtExpr( nullptr );
178 // move env to StmtExpr
179 ret->set_env( assnExpr->get_env() );
180 assnExpr->set_env( nullptr );
181 return ret;
[6eb8948]182 }
183
[c92c09c]184 Type * TupleTypeReplacer::postmutate( TupleType * tupleType ) {
[e6512c8]185 unsigned tupleSize = tupleType->size();
186 if ( ! typeMap.count( tupleSize ) ) {
187 // generate struct type to replace tuple type based on the number of components in the tuple
[94a8123]188 StructDecl * decl = new StructDecl( toString( "_tuple", tupleSize, "_" ) );
[c470ada]189 decl->location = tupleType->location;
[f006f01]190 decl->set_body( true );
[e6512c8]191 for ( size_t i = 0; i < tupleSize; ++i ) {
[f0ecf9b]192 TypeDecl * tyParam = new TypeDecl( toString( "tuple_param_", tupleSize, "_", i ), Type::StorageClasses(), nullptr, TypeDecl::Dtype, true );
[68fe077a]193 decl->get_members().push_back( new ObjectDecl( toString("field_", i ), Type::StorageClasses(), LinkageSpec::C, nullptr, new TypeInstType( Type::Qualifiers(), tyParam->get_name(), tyParam ), nullptr ) );
[d9fa60a]194 decl->get_parameters().push_back( tyParam );
[f006f01]195 }
[e6512c8]196 if ( tupleSize == 0 ) {
[4c8621ac]197 // empty structs are not standard C. Add a dummy field to empty tuples to silence warnings when a compound literal Tuple0 is created.
[68fe077a]198 decl->get_members().push_back( new ObjectDecl( "dummy", Type::StorageClasses(), LinkageSpec::C, nullptr, new BasicType( Type::Qualifiers(), BasicType::SignedInt ), nullptr ) );
[4c8621ac]199 }
[e6512c8]200 typeMap[tupleSize] = decl;
[c92c09c]201 declsToAddBefore.push_back( decl );
[f006f01]202 }
[d9fa60a]203 Type::Qualifiers qualifiers = tupleType->get_qualifiers();
204
[e6512c8]205 StructDecl * decl = typeMap[tupleSize];
[d9fa60a]206 StructInstType * newType = new StructInstType( qualifiers, decl );
[c92c09c]207 for ( auto p : group_iterate( tupleType->get_types(), decl->get_parameters() ) ) {
208 Type * t = std::get<0>(p);
[d9fa60a]209 newType->get_parameters().push_back( new TypeExpr( t->clone() ) );
210 }
211 return newType;
[f006f01]212 }
213
[ab904dc]214 Expression * TupleIndexExpander::postmutate( TupleIndexExpr * tupleExpr ) {
[4f68f6d]215 Expression * tuple = tupleExpr->tuple;
[3c13c03]216 assert( tuple );
[4f68f6d]217 tupleExpr->tuple = nullptr;
218 unsigned int idx = tupleExpr->index;
219 TypeSubstitution * env = tupleExpr->env;
220 tupleExpr->env = nullptr;
[3c13c03]221
[aee472e]222 if ( TupleExpr * tupleExpr = dynamic_cast< TupleExpr * > ( tuple ) ) {
223 if ( ! maybeImpureIgnoreUnique( tupleExpr ) ) {
224 // optimization: definitely pure tuple expr => can reduce to the only relevant component.
225 assert( tupleExpr->exprs.size() > idx );
226 Expression *& expr = *std::next(tupleExpr->exprs.begin(), idx);
227 Expression * ret = expr;
228 ret->env = env;
229 expr = nullptr; // remove from list so it can safely be deleted
230 return ret;
231 }
232 }
[3c13c03]233
[4f68f6d]234 StructInstType * type = strict_dynamic_cast< StructInstType * >( tuple->result );
235 StructDecl * structDecl = type->baseStruct;
236 assert( structDecl->members.size() > idx );
237 Declaration * member = *std::next(structDecl->members.begin(), idx);
[e3e16bc]238 MemberExpr * memExpr = new MemberExpr( strict_dynamic_cast< DeclarationWithType * >( member ), tuple );
[4f68f6d]239 memExpr->env = env;
[d5556a3]240 return memExpr;
[3c13c03]241 }
242
[d5556a3]243 Expression * replaceTupleExpr( Type * result, const std::list< Expression * > & exprs, TypeSubstitution * env ) {
[65660bd]244 if ( result->isVoid() ) {
245 // void result - don't need to produce a value for cascading - just output a chain of comma exprs
246 assert( ! exprs.empty() );
247 std::list< Expression * >::const_iterator iter = exprs.begin();
[d5556a3]248 Expression * expr = new CastExpr( *iter++ );
[65660bd]249 for ( ; iter != exprs.end(); ++iter ) {
[d5556a3]250 expr = new CommaExpr( expr, new CastExpr( *iter ) );
[65660bd]251 }
[d5556a3]252 expr->set_env( env );
[65660bd]253 return expr;
254 } else {
255 // typed tuple expression - produce a compound literal which performs each of the expressions
256 // as a distinct part of its initializer - the produced compound literal may be used as part of
257 // another expression
258 std::list< Initializer * > inits;
259 for ( Expression * expr : exprs ) {
260 inits.push_back( new SingleInit( expr ) );
261 }
[d5556a3]262 Expression * expr = new CompoundLiteralExpr( result, new ListInit( inits ) );
263 expr->set_env( env );
264 return expr;
[3c13c03]265 }
266 }
267
[9f10c4b8]268 Expression * TupleExprExpander::postmutate( TupleExpr * tupleExpr ) {
[65660bd]269 Type * result = tupleExpr->get_result();
270 std::list< Expression * > exprs = tupleExpr->get_exprs();
271 assert( result );
[d5556a3]272 TypeSubstitution * env = tupleExpr->get_env();
[65660bd]273
[68f9c43]274 // remove data from shell
[65660bd]275 tupleExpr->set_result( nullptr );
276 tupleExpr->get_exprs().clear();
[d5556a3]277 tupleExpr->set_env( nullptr );
[65660bd]278
[d5556a3]279 return replaceTupleExpr( result, exprs, env );
[65660bd]280 }
281
282 Type * makeTupleType( const std::list< Expression * > & exprs ) {
283 // produce the TupleType which aggregates the types of the exprs
[62423350]284 std::list< Type * > types;
285 Type::Qualifiers qualifiers( Type::Const | Type::Volatile | Type::Restrict | Type::Lvalue | Type::Atomic | Type::Mutex );
[3c13c03]286 for ( Expression * expr : exprs ) {
287 assert( expr->get_result() );
[65660bd]288 if ( expr->get_result()->isVoid() ) {
289 // if the type of any expr is void, the type of the entire tuple is void
290 return new VoidType( Type::Qualifiers() );
291 }
[3c13c03]292 Type * type = expr->get_result()->clone();
[62423350]293 types.push_back( type );
[65660bd]294 // the qualifiers on the tuple type are the qualifiers that exist on all component types
[3c13c03]295 qualifiers &= type->get_qualifiers();
296 } // for
[907eccb]297 if ( exprs.empty() ) qualifiers = Type::Qualifiers();
[62423350]298 return new TupleType( qualifiers, types );
[3c13c03]299 }
[65660bd]300
[8bf784a]301 TypeInstType * isTtype( Type * type ) {
302 if ( TypeInstType * inst = dynamic_cast< TypeInstType * >( type ) ) {
[0b150ec]303 if ( inst->get_baseType() && inst->get_baseType()->get_kind() == TypeDecl::Ttype ) {
[8bf784a]304 return inst;
305 }
306 }
307 return nullptr;
308 }
309
[65660bd]310 namespace {
311 /// determines if impurity (read: side-effects) may exist in a piece of code. Currently gives a very crude approximation, wherein any function call expression means the code may be impure
[027c496]312 struct ImpurityDetector : public WithShortCircuiting {
[9f10c4b8]313 ImpurityDetector( bool ignoreUnique ) : ignoreUnique( ignoreUnique ) {}
314
[027c496]315 void previsit( ApplicationExpr * appExpr ) {
316 visit_children = false;
[b7b8674]317 if ( DeclarationWithType * function = InitTweak::getFunction( appExpr ) ) {
318 if ( function->get_linkage() == LinkageSpec::Intrinsic ) {
319 if ( function->get_name() == "*?" || function->get_name() == "?[?]" ) {
320 // intrinsic dereference, subscript are pure, but need to recursively look for impurity
[027c496]321 visit_children = true;
[b7b8674]322 return;
323 }
324 }
325 }
326 maybeImpure = true;
327 }
[027c496]328 void previsit( UntypedExpr * ) { maybeImpure = true; visit_children = false; }
329 void previsit( UniqueExpr * ) {
[9f10c4b8]330 if ( ignoreUnique ) {
331 // bottom out at unique expression.
332 // The existence of a unique expression doesn't change the purity of an expression.
333 // That is, even if the wrapped expression is impure, the wrapper protects the rest of the expression.
[027c496]334 visit_children = false;
[9f10c4b8]335 return;
336 }
337 }
338
[65660bd]339 bool maybeImpure = false;
[9f10c4b8]340 bool ignoreUnique;
[65660bd]341 };
342 } // namespace
343
344 bool maybeImpure( Expression * expr ) {
[027c496]345 PassVisitor<ImpurityDetector> detector( false );
[9f10c4b8]346 expr->accept( detector );
[027c496]347 return detector.pass.maybeImpure;
[9f10c4b8]348 }
349
350 bool maybeImpureIgnoreUnique( Expression * expr ) {
[027c496]351 PassVisitor<ImpurityDetector> detector( true );
[65660bd]352 expr->accept( detector );
[027c496]353 return detector.pass.maybeImpure;
[65660bd]354 }
[6eb8948]355} // namespace Tuples
356
357// Local Variables: //
358// tab-width: 4 //
359// mode: c++ //
360// compile-command: "make install" //
361// End: //
Note: See TracBrowser for help on using the repository browser.