source: src/InitTweak/InitTweak.cc@ e491159

ADT aaron-thesis arm-eh ast-experimental cleanup-dtors ctor 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 e491159 was 9b4c936, checked in by Thierry Delisle <tdelisle@…>, 9 years ago

fixed memory leaks in init expander

  • Property mode set to 100644
File size: 15.4 KB
Line 
1#include <algorithm>
2#include "InitTweak.h"
3#include "SynTree/Visitor.h"
4#include "SynTree/Statement.h"
5#include "SynTree/Initializer.h"
6#include "SynTree/Expression.h"
7#include "SynTree/Attribute.h"
8#include "GenPoly/GenPoly.h"
9
10namespace InitTweak {
11 namespace {
12 class HasDesignations : public Visitor {
13 public:
14 bool hasDesignations = false;
15 template<typename Init>
16 void handleInit( Init * init ) {
17 if ( ! init->get_designators().empty() ) hasDesignations = true;
18 else Visitor::visit( init );
19 }
20 virtual void visit( SingleInit * singleInit ) { handleInit( singleInit); }
21 virtual void visit( ListInit * listInit ) { handleInit( listInit); }
22 };
23
24 class InitFlattener : public Visitor {
25 public:
26 virtual void visit( SingleInit * singleInit );
27 virtual void visit( ListInit * listInit );
28 std::list< Expression * > argList;
29 };
30
31 void InitFlattener::visit( SingleInit * singleInit ) {
32 argList.push_back( singleInit->get_value()->clone() );
33 }
34
35 void InitFlattener::visit( ListInit * listInit ) {
36 // flatten nested list inits
37 std::list<Initializer*>::iterator it = listInit->begin();
38 for ( ; it != listInit->end(); ++it ) {
39 (*it)->accept( *this );
40 }
41 }
42 }
43
44 std::list< Expression * > makeInitList( Initializer * init ) {
45 InitFlattener flattener;
46 maybeAccept( init, flattener );
47 return flattener.argList;
48 }
49
50 bool isDesignated( Initializer * init ) {
51 HasDesignations finder;
52 maybeAccept( init, finder );
53 return finder.hasDesignations;
54 }
55
56 class InitExpander::ExpanderImpl {
57 public:
58 virtual std::list< Expression * > next( std::list< Expression * > & indices ) = 0;
59 virtual Statement * buildListInit( UntypedExpr * callExpr, std::list< Expression * > & indices ) = 0;
60 };
61
62 class InitImpl : public InitExpander::ExpanderImpl {
63 public:
64 InitImpl( Initializer * init ) : init( init ) {}
65
66 virtual std::list< Expression * > next( std::list< Expression * > & indices ) {
67 // this is wrong, but just a placeholder for now
68 // if ( ! flattened ) flatten( indices );
69 // return ! inits.empty() ? makeInitList( inits.front() ) : std::list< Expression * >();
70 return makeInitList( init );
71 }
72
73 virtual Statement * buildListInit( UntypedExpr * callExpr, std::list< Expression * > & indices );
74 private:
75 Initializer * init;
76 };
77
78 class ExprImpl : public InitExpander::ExpanderImpl {
79 public:
80 ExprImpl( Expression * expr ) : arg( expr ) {}
81
82 ~ExprImpl() { delete arg; }
83
84 virtual std::list< Expression * > next( std::list< Expression * > & indices ) {
85 std::list< Expression * > ret;
86 Expression * expr = maybeClone( arg );
87 if ( expr ) {
88 for ( std::list< Expression * >::reverse_iterator it = indices.rbegin(); it != indices.rend(); ++it ) {
89 // go through indices and layer on subscript exprs ?[?]
90 ++it;
91 UntypedExpr * subscriptExpr = new UntypedExpr( new NameExpr( "?[?]") );
92 subscriptExpr->get_args().push_back( expr );
93 subscriptExpr->get_args().push_back( (*it)->clone() );
94 expr = subscriptExpr;
95 }
96 ret.push_back( expr );
97 }
98 return ret;
99 }
100
101 virtual Statement * buildListInit( UntypedExpr * callExpr, std::list< Expression * > & indices );
102 private:
103 Expression * arg;
104 };
105
106 InitExpander::InitExpander( Initializer * init ) : expander( new InitImpl( init ) ) {}
107
108 InitExpander::InitExpander( Expression * expr ) : expander( new ExprImpl( expr ) ) {}
109
110 std::list< Expression * > InitExpander::operator*() {
111 return cur;
112 }
113
114 InitExpander & InitExpander::operator++() {
115 cur = expander->next( indices );
116 return *this;
117 }
118
119 // use array indices list to build switch statement
120 void InitExpander::addArrayIndex( Expression * index, Expression * dimension ) {
121 indices.push_back( index );
122 indices.push_back( dimension );
123 }
124
125 void InitExpander::clearArrayIndices() {
126 deleteAll( indices );
127 indices.clear();
128 }
129
130 namespace {
131 /// given index i, dimension d, initializer init, and callExpr f, generates
132 /// if (i < d) f(..., init)
133 /// ++i;
134 /// so that only elements within the range of the array are constructed
135 template< typename OutIterator >
136 void buildCallExpr( UntypedExpr * callExpr, Expression * index, Expression * dimension, Initializer * init, OutIterator out ) {
137 UntypedExpr * cond = new UntypedExpr( new NameExpr( "?<?") );
138 cond->get_args().push_back( index->clone() );
139 cond->get_args().push_back( dimension->clone() );
140
141 std::list< Expression * > args = makeInitList( init );
142 callExpr->get_args().splice( callExpr->get_args().end(), args );
143
144 *out++ = new IfStmt( noLabels, cond, new ExprStmt( noLabels, callExpr ), NULL );
145
146 UntypedExpr * increment = new UntypedExpr( new NameExpr( "++?" ) );
147 increment->get_args().push_back( new AddressExpr( index->clone() ) );
148 *out++ = new ExprStmt( noLabels, increment );
149 }
150
151 template< typename OutIterator >
152 void build( UntypedExpr * callExpr, InitExpander::IndexList::iterator idx, InitExpander::IndexList::iterator idxEnd, Initializer * init, OutIterator out ) {
153 if ( idx == idxEnd ) return;
154 Expression * index = *idx++;
155 assert( idx != idxEnd );
156 Expression * dimension = *idx++;
157
158 // xxx - may want to eventually issue a warning here if we can detect
159 // that the number of elements exceeds to dimension of the array
160 if ( idx == idxEnd ) {
161 if ( ListInit * listInit = dynamic_cast< ListInit * >( init ) ) {
162 for ( Initializer * init : *listInit ) {
163 buildCallExpr( callExpr->clone(), index, dimension, init, out );
164 }
165 } else {
166 buildCallExpr( callExpr->clone(), index, dimension, init, out );
167 }
168 } else {
169 std::list< Statement * > branches;
170
171 unsigned long cond = 0;
172 ListInit * listInit = dynamic_cast< ListInit * >( init );
173 if ( ! listInit ) {
174 // xxx - this shouldn't be an error, but need a way to
175 // terminate without creating output, so should catch this error
176 throw SemanticError( "unbalanced list initializers" );
177 }
178
179 static UniqueName targetLabel( "L__autogen__" );
180 Label switchLabel( targetLabel.newName(), 0, std::list< Attribute * >{ new Attribute("unused") } );
181 for ( Initializer * init : *listInit ) {
182 Expression * condition;
183 // check for designations
184 // if ( init-> ) {
185 condition = new ConstantExpr( Constant::from_ulong( cond ) );
186 ++cond;
187 // } else {
188 // condition = // ... take designation
189 // cond = // ... take designation+1
190 // }
191 std::list< Statement * > stmts;
192 build( callExpr, idx, idxEnd, init, back_inserter( stmts ) );
193 stmts.push_back( new BranchStmt( noLabels, switchLabel, BranchStmt::Break ) );
194 CaseStmt * caseStmt = new CaseStmt( noLabels, condition, stmts );
195 branches.push_back( caseStmt );
196 }
197 *out++ = new SwitchStmt( noLabels, index->clone(), branches );
198 *out++ = new NullStmt( std::list<Label>{ switchLabel } );
199 }
200 }
201 }
202
203 // if array came with an initializer list: initialize each element
204 // may have more initializers than elements in the array - need to check at each index that
205 // we haven't exceeded size.
206 // may have fewer initializers than elements in the array - need to default construct
207 // remaining elements.
208 // To accomplish this, generate switch statement, consuming all of expander's elements
209 Statement * InitImpl::buildListInit( UntypedExpr * dst, std::list< Expression * > & indices ) {
210 if ( ! init ) return NULL;
211 CompoundStmt * block = new CompoundStmt( noLabels );
212 build( dst, indices.begin(), indices.end(), init, back_inserter( block->get_kids() ) );
213 if ( block->get_kids().empty() ) {
214 delete block;
215 return NULL;
216 } else {
217 init = NULL; // init was consumed in creating the list init
218 return block;
219 }
220 }
221
222 Statement * ExprImpl::buildListInit( UntypedExpr * dst, std::list< Expression * > & indices ) {
223 return NULL;
224 }
225
226 Statement * InitExpander::buildListInit( UntypedExpr * dst ) {
227 return expander->buildListInit( dst, indices );
228 }
229
230 bool tryConstruct( ObjectDecl * objDecl ) {
231 return ! LinkageSpec::isBuiltin( objDecl->get_linkage() ) &&
232 (objDecl->get_init() == NULL ||
233 ( objDecl->get_init() != NULL && objDecl->get_init()->get_maybeConstructed() )) &&
234 ! isDesignated( objDecl->get_init() )
235 && objDecl->get_storageClass() != DeclarationNode::Extern;
236 }
237
238 class CallFinder : public Visitor {
239 public:
240 typedef Visitor Parent;
241 CallFinder( const std::list< std::string > & names ) : names( names ) {}
242
243 virtual void visit( ApplicationExpr * appExpr ) {
244 handleCallExpr( appExpr );
245 }
246
247 virtual void visit( UntypedExpr * untypedExpr ) {
248 handleCallExpr( untypedExpr );
249 }
250
251 std::list< Expression * > * matches;
252 private:
253 const std::list< std::string > names;
254
255 template< typename CallExpr >
256 void handleCallExpr( CallExpr * expr ) {
257 Parent::visit( expr );
258 std::string fname = getFunctionName( expr );
259 if ( std::find( names.begin(), names.end(), fname ) != names.end() ) {
260 matches->push_back( expr );
261 }
262 }
263 };
264
265 void collectCtorDtorCalls( Statement * stmt, std::list< Expression * > & matches ) {
266 static CallFinder finder( std::list< std::string >{ "?{}", "^?{}" } );
267 finder.matches = &matches;
268 maybeAccept( stmt, finder );
269 }
270
271 Expression * getCtorDtorCall( Statement * stmt ) {
272 std::list< Expression * > matches;
273 collectCtorDtorCalls( stmt, matches );
274 assert( matches.size() <= 1 );
275 return matches.size() == 1 ? matches.front() : NULL;
276 }
277
278 namespace {
279 VariableExpr * getCalledFunction( ApplicationExpr * appExpr ) {
280 assert( appExpr );
281 // xxx - it's possible this can be other things, e.g. MemberExpr, so this is insufficient
282 return dynamic_cast< VariableExpr * >( appExpr->get_function() );
283 }
284 }
285
286 ApplicationExpr * isIntrinsicCallExpr( Expression * expr ) {
287 ApplicationExpr * appExpr = dynamic_cast< ApplicationExpr * >( expr );
288 if ( ! appExpr ) return NULL;
289 VariableExpr * function = getCalledFunction( appExpr );
290 assert( function );
291 // check for Intrinsic only - don't want to remove all overridable ctor/dtors because autogenerated ctor/dtor
292 // will call all member dtors, and some members may have a user defined dtor.
293 return function->get_var()->get_linkage() == LinkageSpec::Intrinsic ? appExpr : NULL;
294 }
295
296 namespace {
297 template <typename Predicate>
298 bool allofCtorDtor( Statement * stmt, const Predicate & pred ) {
299 std::list< Expression * > callExprs;
300 collectCtorDtorCalls( stmt, callExprs );
301 // if ( callExprs.empty() ) return false; // xxx - do I still need this check?
302 return std::all_of( callExprs.begin(), callExprs.end(), pred);
303 }
304 }
305
306 bool isIntrinsicSingleArgCallStmt( Statement * stmt ) {
307 return allofCtorDtor( stmt, []( Expression * callExpr ){
308 if ( ApplicationExpr * appExpr = isIntrinsicCallExpr( callExpr ) ) {
309 assert( ! appExpr->get_function()->get_results().empty() );
310 FunctionType *funcType = GenPoly::getFunctionType( appExpr->get_function()->get_results().front() );
311 assert( funcType );
312 return funcType->get_parameters().size() == 1;
313 }
314 return false;
315 });
316 }
317
318 bool isIntrinsicCallStmt( Statement * stmt ) {
319 return allofCtorDtor( stmt, []( Expression * callExpr ) {
320 return isIntrinsicCallExpr( callExpr );
321 });
322 }
323
324 namespace {
325 template<typename CallExpr>
326 Expression *& callArg( CallExpr * callExpr, unsigned int pos ) {
327 if ( pos >= callExpr->get_args().size() ) assert( false && "asking for argument that doesn't exist. Return NULL/throw exception?" );
328 for ( Expression *& arg : callExpr->get_args() ) {
329 if ( pos == 0 ) return arg;
330 pos--;
331 }
332 assert( false );
333 }
334 }
335
336 Expression *& getCallArg( Expression * callExpr, unsigned int pos ) {
337 if ( ApplicationExpr * appExpr = dynamic_cast< ApplicationExpr * >( callExpr ) ) {
338 return callArg( appExpr, pos );
339 } else if ( UntypedExpr * untypedExpr = dynamic_cast< UntypedExpr * >( callExpr ) ) {
340 return callArg( untypedExpr, pos );
341 } else {
342 assert( false && "Unexpected expression type passed to getCallArg" );
343 }
344 }
345
346 namespace {
347 std::string funcName( Expression * func ) {
348 if ( NameExpr * nameExpr = dynamic_cast< NameExpr * >( func ) ) {
349 return nameExpr->get_name();
350 } else if ( VariableExpr * varExpr = dynamic_cast< VariableExpr * >( func ) ) {
351 return varExpr->get_var()->get_name();
352 } else if ( CastExpr * castExpr = dynamic_cast< CastExpr * >( func ) ) {
353 return funcName( castExpr->get_arg() );
354 } else {
355 assert( false && "Unexpected expression type being called as a function in call expression" );
356 }
357 }
358 }
359
360 std::string getFunctionName( Expression * expr ) {
361 if ( ApplicationExpr * appExpr = dynamic_cast< ApplicationExpr * >( expr ) ) {
362 return funcName( appExpr->get_function() );
363 } else if ( UntypedExpr * untypedExpr = dynamic_cast< UntypedExpr * > ( expr ) ) {
364 return funcName( untypedExpr->get_function() );
365 } else {
366 std::cerr << expr << std::endl;
367 assert( false && "Unexpected expression type passed to getFunctionName" );
368 }
369 }
370
371 Type * getPointerBase( Type * type ) {
372 if ( PointerType * ptrType = dynamic_cast< PointerType * >( type ) ) {
373 return ptrType->get_base();
374 } else if ( ArrayType * arrayType = dynamic_cast< ArrayType * >( type ) ) {
375 return arrayType->get_base();
376 } else {
377 return NULL;
378 }
379 }
380
381 Type * isPointerType( Type * type ) {
382 if ( getPointerBase( type ) ) return type;
383 else return NULL;
384 }
385
386 class ConstExprChecker : public Visitor {
387 public:
388 ConstExprChecker() : isConstExpr( true ) {}
389
390 virtual void visit( ApplicationExpr *applicationExpr ) { isConstExpr = false; }
391 virtual void visit( UntypedExpr *untypedExpr ) { isConstExpr = false; }
392 virtual void visit( NameExpr *nameExpr ) { isConstExpr = false; }
393 virtual void visit( CastExpr *castExpr ) { isConstExpr = false; }
394 virtual void visit( LabelAddressExpr *labAddressExpr ) { isConstExpr = false; }
395 virtual void visit( UntypedMemberExpr *memberExpr ) { isConstExpr = false; }
396 virtual void visit( MemberExpr *memberExpr ) { isConstExpr = false; }
397 virtual void visit( VariableExpr *variableExpr ) { isConstExpr = false; }
398 virtual void visit( ConstantExpr *constantExpr ) { /* bottom out */ }
399 // these might be okay?
400 // virtual void visit( SizeofExpr *sizeofExpr );
401 // virtual void visit( AlignofExpr *alignofExpr );
402 // virtual void visit( UntypedOffsetofExpr *offsetofExpr );
403 // virtual void visit( OffsetofExpr *offsetofExpr );
404 // virtual void visit( OffsetPackExpr *offsetPackExpr );
405 // virtual void visit( AttrExpr *attrExpr );
406 // virtual void visit( CommaExpr *commaExpr );
407 // virtual void visit( LogicalExpr *logicalExpr );
408 // virtual void visit( ConditionalExpr *conditionalExpr );
409 virtual void visit( TupleExpr *tupleExpr ) { isConstExpr = false; }
410 virtual void visit( SolvedTupleExpr *tupleExpr ) { isConstExpr = false; }
411 virtual void visit( TypeExpr *typeExpr ) { isConstExpr = false; }
412 virtual void visit( AsmExpr *asmExpr ) { isConstExpr = false; }
413 virtual void visit( UntypedValofExpr *valofExpr ) { isConstExpr = false; }
414 virtual void visit( CompoundLiteralExpr *compLitExpr ) { isConstExpr = false; }
415
416 bool isConstExpr;
417 };
418
419 bool isConstExpr( Expression * expr ) {
420 if ( expr ) {
421 ConstExprChecker checker;
422 expr->accept( checker );
423 return checker.isConstExpr;
424 }
425 return true;
426 }
427
428 bool isConstExpr( Initializer * init ) {
429 if ( init ) {
430 ConstExprChecker checker;
431 init->accept( checker );
432 return checker.isConstExpr;
433 } // if
434 // for all intents and purposes, no initializer means const expr
435 return true;
436 }
437
438 bool isConstructor( const std::string & str ) { return str == "?{}"; }
439 bool isDestructor( const std::string & str ) { return str == "^?{}"; }
440 bool isCtorDtor( const std::string & str ) { return isConstructor( str ) || isDestructor( str ); }
441}
Note: See TracBrowser for help on using the repository browser.