source: src/Tuples/TupleExpansion.cc@ d82daa1

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 d82daa1 was be9288a, checked in by Thierry Delisle <tdelisle@…>, 8 years ago

Fixed errors made by the clean-up tool

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