source: src/Tuples/TupleExpansion.cc@ 16988e8

ADT aaron-thesis arm-eh ast-experimental cleanup-dtors deferred_resn demangler enum forall-pointer-decay jacob/cs343-translation jenkins-sandbox new-ast new-ast-unique-expr new-env no_list persistent-indexer pthread-emulation qualifiedEnum resolv-new with_gc
Last change on this file since 16988e8 was 027c496, checked in by Rob Schluntz <rschlunt@…>, 8 years ago

Convert ImpurityDetector to PassVisitor

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