source: src/Validate/Autogen.cpp@ d8a3073

stuck-waitfor-destruct
Last change on this file since d8a3073 was d8a3073, checked in by Matthew Au-Yeung <mw2auyeu@…>, 2 months ago

Set top level autogen cfa_linkonce

  • Remove default static and inline
  • Add pass to autogen functions in lib to have default visibility
  • Add fix for union ctor with array constructor passing pointer to array instead of array itself. Previous changes brought light the compilation error.
  • Note: found compilation trying to invoke union operator with array in cfa
  • Property mode set to 100644
File size: 28.4 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// Autogen.cpp -- Generate automatic routines for data types.
8//
9// Author : Andrew Beach
10// Created On : Thu Dec 2 13:44:00 2021
11// Last Modified By : Andrew Beach
12// Last Modified On : Tue Sep 20 16:00:00 2022
13// Update Count : 2
14//
15
16#include "Autogen.hpp"
17
18#include <algorithm> // for count_if
19#include <cassert> // for strict_dynamic_cast, assert, a...
20#include <iterator> // for back_insert_iterator, back_ins...
21#include <list> // for list, _List_iterator, list<>::...
22#include <set> // for set, _Rb_tree_const_iterator
23#include <utility> // for pair
24#include <vector> // for vector
25
26#include "AST/Attribute.hpp"
27#include "AST/Copy.hpp"
28#include "AST/Create.hpp"
29#include "AST/Decl.hpp"
30#include "AST/DeclReplacer.hpp"
31#include "AST/Expr.hpp"
32#include "AST/Inspect.hpp"
33#include "AST/Pass.hpp"
34#include "AST/Stmt.hpp"
35#include "AST/SymbolTable.hpp"
36#include "CodeGen/OperatorTable.hpp" // for isCtorDtor, isCtorDtorAssign
37#include "Common/ScopedMap.hpp" // for ScopedMap<>::const_iterator, S...
38#include "Common/Utility.hpp" // for cloneAll, operator+
39#include "GenPoly/ScopedSet.hpp" // for ScopedSet, ScopedSet<>::iterator
40#include "InitTweak/GenInit.hpp" // for fixReturnStatements
41#include "InitTweak/InitTweak.hpp" // for isAssignment, isCopyConstructor
42#include "SymTab/GenImplicitCall.hpp" // for genImplicitCall
43#include "SymTab/Mangler.hpp" // for Mangler
44#include "CompilationState.hpp"
45
46namespace Validate {
47
48namespace {
49
50// --------------------------------------------------------------------------
51struct AutogenerateRoutines final :
52 public ast::WithDeclsToAdd,
53 public ast::WithShortCircuiting {
54 void previsit( const ast::EnumDecl * enumDecl );
55 void previsit( const ast::StructDecl * structDecl );
56 void previsit( const ast::UnionDecl * structDecl );
57 void previsit( const ast::TypeDecl * typeDecl );
58 void previsit( const ast::TraitDecl * traitDecl );
59 void previsit( const ast::FunctionDecl * functionDecl );
60 void postvisit( const ast::FunctionDecl * functionDecl );
61
62private:
63 // Current level of nested functions.
64 unsigned int functionNesting = 0;
65};
66
67// --------------------------------------------------------------------------
68/// Class used to generate functions for a particular declaration.
69/// Note it isn't really stored, it is just a class for organization and to
70/// help pass around some of the common arguments.
71class FuncGenerator {
72public:
73 std::list<ast::ptr<ast::Decl>> definitions;
74
75 FuncGenerator( const ast::Type * type, unsigned int functionNesting ) :
76 type( type ), functionNesting( functionNesting )
77 {}
78
79 /// Generate functions (and forward decls.) and append them to the list.
80 void generateAndAppendFunctions( std::list<ast::ptr<ast::Decl>> & );
81
82 virtual bool shouldAutogen() const = 0;
83protected:
84 const ast::Type * type;
85 unsigned int functionNesting;
86 ast::Linkage::Spec proto_linkage = ast::Linkage::AutoGen;
87
88 // Internal helpers:
89 virtual void genStandardFuncs();
90 void produceDecl( const ast::FunctionDecl * decl );
91
92 const CodeLocation& getLocation() const { return getDecl()->location; }
93 ast::FunctionDecl * genProto( std::string&& name,
94 std::vector<ast::ptr<ast::DeclWithType>>&& params,
95 std::vector<ast::ptr<ast::DeclWithType>>&& returns ) const;
96
97 ast::ObjectDecl * dstParam() const;
98 ast::ObjectDecl * srcParam() const;
99 ast::FunctionDecl * genCtorProto() const;
100 ast::FunctionDecl * genCopyProto() const;
101 ast::FunctionDecl * genDtorProto() const;
102 ast::FunctionDecl * genAssignProto() const;
103 ast::FunctionDecl * genFieldCtorProto( unsigned int fields ) const;
104
105 // Internal Hooks:
106 virtual void genFuncBody( ast::FunctionDecl * decl ) = 0;
107 virtual void genFieldCtors() = 0;
108 virtual bool isConcurrentType() const { return false; }
109 virtual const ast::Decl * getDecl() const = 0;
110};
111
112class StructFuncGenerator final : public FuncGenerator {
113 const ast::StructDecl * decl;
114public:
115 StructFuncGenerator( const ast::StructDecl * decl,
116 const ast::StructInstType * type,
117 unsigned int functionNesting ) :
118 FuncGenerator( type, functionNesting ), decl( decl )
119 {}
120
121 // Built-ins do not use autogeneration.
122 bool shouldAutogen() const final { return !decl->linkage.is_builtin && !structHasFlexibleArray(decl); }
123private:
124 void genFuncBody( ast::FunctionDecl * decl ) final;
125 void genFieldCtors() final;
126 bool isConcurrentType() const final {
127 return decl->is_thread() || decl->is_monitor();
128 }
129 virtual const ast::Decl * getDecl() const final { return decl; }
130
131 /// Generates a single struct member operation.
132 /// (constructor call, destructor call, assignment call)
133 const ast::Stmt * makeMemberOp(
134 const CodeLocation& location,
135 const ast::ObjectDecl * dstParam, const ast::Expr * src,
136 const ast::ObjectDecl * field, ast::FunctionDecl * func,
137 SymTab::LoopDirection direction );
138
139 /// Generates the body of a struct function by iterating the struct members
140 /// (via parameters). Generates default constructor, copy constructor,
141 /// copy assignment, and destructor bodies. No field constructor bodies.
142 template<typename Iterator>
143 void makeFunctionBody( Iterator member, Iterator end,
144 ast::FunctionDecl * func, SymTab::LoopDirection direction );
145
146 /// Generate the body of a constructor which takes parameters that match
147 /// fields. (With arguments for one to all of the fields.)
148 template<typename Iterator>
149 void makeFieldCtorBody( Iterator member, Iterator end,
150 ast::FunctionDecl * func );
151};
152
153class UnionFuncGenerator final : public FuncGenerator {
154 const ast::UnionDecl * decl;
155public:
156 UnionFuncGenerator( const ast::UnionDecl * decl,
157 const ast::UnionInstType * type,
158 unsigned int functionNesting ) :
159 FuncGenerator( type, functionNesting ), decl( decl )
160 {}
161
162 // Built-ins do not use autogeneration.
163 bool shouldAutogen() const final { return !decl->linkage.is_builtin; }
164private:
165 void genFuncBody( ast::FunctionDecl * decl ) final;
166 void genFieldCtors() final;
167 const ast::Decl * getDecl() const final { return decl; }
168
169 /// Generate a single union assignment expression (using memcpy).
170 ast::ExprStmt * makeAssignOp( const CodeLocation& location,
171 const ast::ObjectDecl * dstParam, const ast::ObjectDecl * srcParam );
172};
173
174class EnumFuncGenerator final : public FuncGenerator {
175 const ast::EnumDecl * decl;
176public:
177 EnumFuncGenerator( const ast::EnumDecl * decl,
178 const ast::EnumInstType * type,
179 unsigned int functionNesting ) :
180 FuncGenerator( type, functionNesting ), decl( decl )
181 {
182 // TODO: These functions are somewhere between instrinsic and autogen,
183 // could possibly use a new linkage type. For now we just make the
184 // basic ones intrinsic to code-gen them as C assignments.
185 // const auto & real_type = decl->base;
186 // const auto & basic = real_type.as<ast::BasicType>();
187
188 // if(!real_type || (basic && basic->isInteger())) proto_linkage = ast::Linkage::Intrinsic;
189
190 // Turns other enumeration type into Intrinstic as well to temporarily fix the recursive
191 // construction bug
192 proto_linkage = ast::Linkage::Intrinsic;
193 }
194
195 bool shouldAutogen() const final { return true; }
196private:
197 void genFuncBody( ast::FunctionDecl * decl ) final;
198 void genFieldCtors() final;
199 const ast::Decl * getDecl() const final { return decl; }
200protected:
201 void genStandardFuncs() override;
202};
203
204class TypeFuncGenerator final : public FuncGenerator {
205 const ast::TypeDecl * decl;
206public:
207 TypeFuncGenerator( const ast::TypeDecl * decl,
208 ast::TypeInstType * type,
209 unsigned int functionNesting ) :
210 FuncGenerator( type, functionNesting ), decl( decl )
211 {}
212
213 bool shouldAutogen() const final { return true; }
214 void genFieldCtors() final;
215private:
216 void genFuncBody( ast::FunctionDecl * decl ) final;
217 const ast::Decl * getDecl() const final { return decl; }
218};
219
220// --------------------------------------------------------------------------
221const std::vector<ast::ptr<ast::TypeDecl>>& getGenericParams( const ast::Type * t ) {
222 if ( auto inst = dynamic_cast< const ast::StructInstType * >( t ) ) {
223 return inst->base->params;
224 } else if ( auto inst = dynamic_cast< const ast::UnionInstType * >( t ) ) {
225 return inst->base->params;
226 }
227 static std::vector<ast::ptr<ast::TypeDecl>> const empty;
228 return empty;
229}
230
231/// Changes the freshly-constructed (non-const) decl so that it has the unused attribute.
232ast::ObjectDecl * addUnusedAttribute( ast::ObjectDecl * decl ) {
233 decl->attributes.push_back( new ast::Attribute( "unused" ) );
234 return decl;
235}
236
237// --------------------------------------------------------------------------
238void AutogenerateRoutines::previsit( const ast::EnumDecl * enumDecl ) {
239 if ( !enumDecl->body ) return;
240
241 ast::EnumInstType enumInst( enumDecl->name );
242 enumInst.base = enumDecl;
243
244 EnumFuncGenerator gen( enumDecl, &enumInst, functionNesting );
245 gen.generateAndAppendFunctions( declsToAddAfter );
246}
247
248void AutogenerateRoutines::previsit( const ast::StructDecl * structDecl ) {
249 visit_children = false;
250 if ( !structDecl->body ) return;
251
252 ast::StructInstType structInst( structDecl->name );
253 structInst.base = structDecl;
254 for ( const ast::TypeDecl * typeDecl : structDecl->params ) {
255 structInst.params.push_back( new ast::TypeExpr(
256 typeDecl->location,
257 new ast::TypeInstType( typeDecl )
258 ) );
259 }
260 StructFuncGenerator gen( structDecl, &structInst, functionNesting );
261 gen.generateAndAppendFunctions( declsToAddAfter );
262}
263
264void AutogenerateRoutines::previsit( const ast::UnionDecl * unionDecl ) {
265 visit_children = false;
266 if ( !unionDecl->body ) return;
267
268 ast::UnionInstType unionInst( unionDecl->name );
269 unionInst.base = unionDecl;
270 for ( const ast::TypeDecl * typeDecl : unionDecl->params ) {
271 unionInst.params.push_back( new ast::TypeExpr(
272 unionDecl->location,
273 new ast::TypeInstType( typeDecl )
274 ) );
275 }
276 UnionFuncGenerator gen( unionDecl, &unionInst, functionNesting );
277 gen.generateAndAppendFunctions( declsToAddAfter );
278}
279
280/// Generate ctor/dtors/assign for typedecls, e.g., otype T = int *;
281void AutogenerateRoutines::previsit( const ast::TypeDecl * typeDecl ) {
282 if ( !typeDecl->base ) return;
283
284 ast::TypeInstType refType( typeDecl->name, typeDecl );
285 TypeFuncGenerator gen( typeDecl, &refType, functionNesting );
286 gen.generateAndAppendFunctions( declsToAddAfter );
287}
288
289void AutogenerateRoutines::previsit( const ast::TraitDecl * ) {
290 // Ensure that we don't add assignment ops for types defined as part of the trait
291 visit_children = false;
292}
293
294void AutogenerateRoutines::previsit( const ast::FunctionDecl * ) {
295 // Track whether we're currently in a function.
296 // Can ignore function type idiosyncrasies, because function type can never
297 // declare a new type.
298 functionNesting += 1;
299}
300
301void AutogenerateRoutines::postvisit( const ast::FunctionDecl * ) {
302 functionNesting -= 1;
303}
304
305void FuncGenerator::generateAndAppendFunctions(
306 std::list<ast::ptr<ast::Decl>> & decls ) {
307 if ( !shouldAutogen() ) return;
308
309 // Generate the functions (they go into forwards and definitions).
310 genStandardFuncs();
311 genFieldCtors();
312
313 // Now export the lists contents.
314// decls.splice( decls.end(), forwards ); // mlb wip: delete me
315 decls.splice( decls.end(), definitions );
316}
317
318void FuncGenerator::produceDecl( const ast::FunctionDecl * decl ) {
319 assert( nullptr != decl->stmts );
320 assert( decl->type_params.size() == getGenericParams( type ).size() );
321
322 definitions.push_back( decl );
323}
324
325void replaceAll( std::vector<ast::ptr<ast::DeclWithType>> & dwts,
326 const ast::DeclReplacer::TypeMap & map ) {
327 for ( auto & dwt : dwts ) {
328 dwt = strict_dynamic_cast<const ast::DeclWithType *>(
329 ast::DeclReplacer::replace( dwt, map ) );
330 }
331}
332
333/// Generates a basic prototype function declaration.
334ast::FunctionDecl * FuncGenerator::genProto( std::string&& name,
335 std::vector<ast::ptr<ast::DeclWithType>>&& params,
336 std::vector<ast::ptr<ast::DeclWithType>>&& returns ) const {
337
338 // Handle generic prameters and assertions, if any.
339 auto const & old_type_params = getGenericParams( type );
340 ast::DeclReplacer::TypeMap oldToNew;
341 std::vector<ast::ptr<ast::TypeDecl>> type_params;
342 std::vector<ast::ptr<ast::DeclWithType>> assertions;
343 for ( auto & old_param : old_type_params ) {
344 ast::TypeDecl * decl = ast::deepCopy( old_param );
345 decl->init = nullptr;
346 splice( assertions, decl->assertions );
347 oldToNew.emplace( old_param, decl );
348 type_params.push_back( decl );
349 }
350 replaceAll( params, oldToNew );
351 replaceAll( returns, oldToNew );
352 replaceAll( assertions, oldToNew );
353
354 bool isTopLevel = ( 0 == functionNesting );
355 bool isCfaLinkage = getDecl()->linkage.is_mangled;
356
357 ast::Storage::Classes storage = ast::Storage::Classes(); // Default no static
358 ast::Function::Specs funcSpec; // Default no inline
359 std::vector<ast::ptr<ast::Attribute>> attributes;
360 if ( !isTopLevel ) {
361 // Nested: use inline, no linkonce needed for local types.
362 funcSpec = ast::Function::Specs( ast::Function::Inline );
363 } else if ( isCfaLinkage ) {
364 // Top-level CFA type: use linkonce for cross-TU deduplication.
365 attributes.push_back( new ast::Attribute( "cfa_linkonce" ) );
366 } else {
367 // Top-level C type: keep original static inline to avoid
368 // exposing latent issues in auto-generated code for system types.
369 storage = ast::Storage::Static;
370 funcSpec = ast::Function::Specs( ast::Function::Inline );
371 }
372
373 ast::FunctionDecl * decl = new ast::FunctionDecl(
374 // Auto-generated routines use the type declaration's location.
375 getLocation(),
376 std::move( name ),
377 std::move( type_params ),
378 std::move( assertions ),
379 std::move( params ),
380 std::move( returns ),
381 // Only a prototype, no body.
382 nullptr,
383 storage,
384 proto_linkage,
385 std::move( attributes ),
386 funcSpec );
387 decl->fixUniqueId();
388 return decl;
389}
390
391ast::ObjectDecl * FuncGenerator::dstParam() const {
392 return addUnusedAttribute(
393 new ast::ObjectDecl( getLocation(), "_dst",
394 new ast::ReferenceType( ast::deepCopy( type ) ) ) );
395}
396
397ast::ObjectDecl * FuncGenerator::srcParam() const {
398 return addUnusedAttribute(
399 new ast::ObjectDecl( getLocation(), "_src",
400 ast::deepCopy( type ) ) );
401}
402
403/// Use the current type T to create `void ?{}(T & _dst)`.
404ast::FunctionDecl * FuncGenerator::genCtorProto() const {
405 return genProto( "?{}", { dstParam() }, {} );
406}
407
408/// Use the current type T to create `void ?{}(T & _dst, T _src)`.
409ast::FunctionDecl * FuncGenerator::genCopyProto() const {
410 return genProto( "?{}", { dstParam(), srcParam() }, {} );
411}
412
413/// Use the current type T to create `void ^?{}(T & _dst)`.
414ast::FunctionDecl * FuncGenerator::genDtorProto() const {
415 // The destructor must be mutex on a concurrent type.
416 auto dst = dstParam();
417 if ( isConcurrentType() ) {
418 add_qualifiers( dst->type, ast::CV::Qualifiers( ast::CV::Mutex ) );
419 }
420 return genProto( "^?{}", { dst }, {} );
421}
422
423/// Use the current type T to create `T ?=?(T & _dst, T _src)`.
424ast::FunctionDecl * FuncGenerator::genAssignProto() const {
425 // Only the name is different, so just reuse the generation function.
426 auto retval = srcParam();
427 retval->name = "_ret";
428 return genProto( "?=?", { dstParam(), srcParam() }, { retval } );
429}
430
431// This one can return null if the last field is an unnamed bitfield.
432ast::FunctionDecl * FuncGenerator::genFieldCtorProto(
433 unsigned int fields ) const {
434 assert( 0 < fields );
435 auto aggr = strict_dynamic_cast<const ast::AggregateDecl *>( getDecl() );
436
437 std::vector<ast::ptr<ast::DeclWithType>> params = { dstParam() };
438 for ( unsigned int index = 0 ; index < fields ; ++index ) {
439 auto member = aggr->members[index].strict_as<ast::DeclWithType>();
440 if ( ast::isUnnamedBitfield(
441 dynamic_cast<const ast::ObjectDecl *>( member ) ) ) {
442 if ( index == fields - 1 ) {
443 return nullptr;
444 }
445 continue;
446 }
447
448 auto * paramType = ast::deepCopy( member->get_type() );
449 erase_if( paramType->attributes, []( ast::Attribute const * attr ){
450 return !attr->isValidOnFuncParam();
451 } );
452 ast::ObjectDecl * param = new ast::ObjectDecl(
453 getLocation(), member->name, paramType );
454 for ( auto & attr : member->attributes ) {
455 if ( attr->isValidOnFuncParam() ) {
456 param->attributes.push_back( attr );
457 }
458 }
459 params.emplace_back( param );
460 }
461 return genProto( "?{}", std::move( params ), {} );
462}
463
464void appendReturnThis( ast::FunctionDecl * decl ) {
465 assert( 1 <= decl->params.size() );
466 assert( 1 == decl->returns.size() );
467 assert( decl->stmts );
468
469 const CodeLocation& location = (decl->stmts->kids.empty())
470 ? decl->stmts->location : decl->stmts->kids.back()->location;
471 const ast::DeclWithType * thisParam = decl->params.front();
472 decl->stmts.get_and_mutate()->push_back(
473 new ast::ReturnStmt( location,
474 new ast::VariableExpr( location, thisParam )
475 )
476 );
477}
478
479void FuncGenerator::genStandardFuncs() {
480 // The order here determines the order that these functions are generated.
481 // Assignment should come last since it uses copy constructor in return.
482 ast::FunctionDecl *(FuncGenerator::*standardProtos[4])() const = {
483 &FuncGenerator::genCtorProto, &FuncGenerator::genCopyProto,
484 &FuncGenerator::genDtorProto, &FuncGenerator::genAssignProto };
485 for ( auto & generator : standardProtos ) {
486 ast::FunctionDecl * decl = (this->*generator)();
487 genFuncBody( decl );
488 if ( CodeGen::isAssignment( decl->name ) ) {
489 appendReturnThis( decl );
490 }
491 produceDecl( decl );
492 }
493}
494
495void StructFuncGenerator::genFieldCtors() {
496 // The field constructors are only generated if the default constructor
497 // and copy constructor are both generated, since the need both.
498 unsigned numCtors = std::count_if( definitions.begin(), definitions.end(),
499 [](const ast::Decl * decl){ return CodeGen::isConstructor( decl->name ); }
500 );
501 if ( 2 != numCtors ) return;
502
503 for ( unsigned int num = 1 ; num <= decl->members.size() ; ++num ) {
504 ast::FunctionDecl * ctor = genFieldCtorProto( num );
505 if ( nullptr == ctor ) {
506 continue;
507 }
508 makeFieldCtorBody( decl->members.begin(), decl->members.end(), ctor );
509 produceDecl( ctor );
510 }
511}
512
513void StructFuncGenerator::genFuncBody( ast::FunctionDecl * functionDecl ) {
514 // Generate appropriate calls to member constructors and assignment.
515 // Destructor needs to do everything in reverse,
516 // so pass "forward" based on whether the function is a destructor
517 if ( CodeGen::isDestructor( functionDecl->name ) ) {
518 makeFunctionBody( decl->members.rbegin(), decl->members.rend(),
519 functionDecl, SymTab::LoopBackward );
520 } else {
521 makeFunctionBody( decl->members.begin(), decl->members.end(),
522 functionDecl, SymTab::LoopForward );
523 }
524}
525
526const ast::Stmt * StructFuncGenerator::makeMemberOp(
527 const CodeLocation& location, const ast::ObjectDecl * dstParam,
528 const ast::Expr * src, const ast::ObjectDecl * field,
529 ast::FunctionDecl * func, SymTab::LoopDirection direction ) {
530 InitTweak::InitExpander srcParam( src );
531 // Assign to destination.
532 ast::MemberExpr * dstSelect = new ast::MemberExpr(
533 location,
534 field,
535 new ast::CastExpr(
536 location,
537 new ast::VariableExpr( location, dstParam ),
538 dstParam->type.strict_as<ast::ReferenceType>()->base
539 )
540 );
541 const ast::Stmt * stmt = genImplicitCall(
542 srcParam, dstSelect, location, func->name,
543 field, direction
544 );
545 // This could return the above directly, except the generated code is
546 // built using the structure's members and that means all the scoped
547 // names (the forall parameters) are incorrect. This corrects them.
548 if ( stmt && !decl->params.empty() ) {
549 ast::DeclReplacer::TypeMap oldToNew;
550 for ( auto pair : group_iterate( decl->params, func->type_params ) ) {
551 oldToNew.emplace( std::get<0>(pair), std::get<1>(pair) );
552 }
553 auto node = ast::DeclReplacer::replace( stmt, oldToNew );
554 stmt = strict_dynamic_cast<const ast::Stmt *>( node );
555 }
556 return stmt;
557}
558
559template<typename Iterator>
560void StructFuncGenerator::makeFunctionBody( Iterator current, Iterator end,
561 ast::FunctionDecl * func, SymTab::LoopDirection direction ) {
562 // Trying to get the best code location. Should probably use a helper or
563 // just figure out what that would be given where this is called.
564 assert( nullptr == func->stmts );
565 const CodeLocation& location = func->location;
566
567 ast::CompoundStmt * stmts = new ast::CompoundStmt( location );
568
569 for ( ; current != end ; ++current ) {
570 const ast::ptr<ast::Decl> & member = *current;
571 auto field = member.as<ast::ObjectDecl>();
572 if ( nullptr == field ) {
573 continue;
574 }
575
576 // Don't assign to constant members (but do construct/destruct them).
577 if ( CodeGen::isAssignment( func->name ) ) {
578 // For array types we need to strip off the array layers.
579 const ast::Type * type = field->get_type();
580 while ( auto at = dynamic_cast<const ast::ArrayType *>( type ) ) {
581 type = at->base;
582 }
583 if ( type->is_const() ) {
584 continue;
585 }
586 }
587
588 assert( !func->params.empty() );
589 const ast::ObjectDecl * dstParam =
590 func->params.front().strict_as<ast::ObjectDecl>();
591 const ast::ObjectDecl * srcParam = nullptr;
592 if ( 2 == func->params.size() ) {
593 srcParam = func->params.back().strict_as<ast::ObjectDecl>();
594 }
595
596 ast::MemberExpr * srcSelect = (srcParam) ? new ast::MemberExpr(
597 location, field, new ast::VariableExpr( location, srcParam )
598 ) : nullptr;
599 const ast::Stmt * stmt =
600 makeMemberOp( location, dstParam, srcSelect, field, func, direction );
601
602 if ( nullptr != stmt ) {
603 stmts->kids.emplace_back( stmt );
604 }
605 }
606
607 func->stmts = stmts;
608}
609
610template<typename Iterator>
611void StructFuncGenerator::makeFieldCtorBody( Iterator current, Iterator end,
612 ast::FunctionDecl * func ) {
613 const CodeLocation& location = func->location;
614 auto & params = func->params;
615 // Need at least the constructed parameter and one field parameter.
616 assert( 2 <= params.size() );
617
618 ast::CompoundStmt * stmts = new ast::CompoundStmt( location );
619
620 auto dstParam = params.front().strict_as<ast::ObjectDecl>();
621 // Skip over the 'this' parameter.
622 for ( auto param = params.begin() + 1 ; current != end ; ++current ) {
623 const ast::ptr<ast::Decl> & member = *current;
624 const ast::Stmt * stmt = nullptr;
625 auto field = member.as<ast::ObjectDecl>();
626 // Not sure why it could be null.
627 // Don't make a function for a parameter that is an unnamed bitfield.
628 if ( nullptr == field || ast::isUnnamedBitfield( field ) ) {
629 continue;
630 // Matching Parameter: Initialize the field by copy.
631 } else if ( params.end() != param ) {
632 const ast::Expr *srcSelect = new ast::VariableExpr(
633 func->location, param->get() );
634 stmt = makeMemberOp( location, dstParam, srcSelect, field, func, SymTab::LoopForward );
635 ++param;
636 // No Matching Parameter: Initialize the field by default constructor.
637 } else {
638 stmt = makeMemberOp( location, dstParam, nullptr, field, func, SymTab::LoopForward );
639 }
640
641 if ( nullptr != stmt ) {
642 stmts->kids.emplace_back( stmt );
643 }
644 }
645 func->stmts = stmts;
646}
647
648void UnionFuncGenerator::genFieldCtors() {
649 // Field constructors are only generated if default and copy constructor
650 // are generated, since they need access to both
651 unsigned numCtors = std::count_if( definitions.begin(), definitions.end(),
652 []( const ast::Decl * d ){ return CodeGen::isConstructor( d->name ); }
653 );
654 if ( 2 != numCtors ) {
655 return;
656 }
657
658 // Create a constructor which takes the first member type as a
659 // parameter. For example for `union A { int x; char y; };` generate
660 // a function with signature `void ?{}(A *, int)`. This mimics C's
661 // behaviour which initializes the first member of the union.
662
663 // Still, there must be some members.
664 if ( !decl->members.empty() ) {
665 ast::FunctionDecl * ctor = genFieldCtorProto( 1 );
666 if ( nullptr == ctor ) {
667 return;
668 }
669 auto params = ctor->params;
670 auto dstParam = params.front().strict_as<ast::ObjectDecl>();
671 auto srcParam = params.back().strict_as<ast::ObjectDecl>();
672 ctor->stmts = new ast::CompoundStmt( getLocation(),
673 { makeAssignOp( getLocation(), dstParam, srcParam ) }
674 );
675 produceDecl( ctor );
676 }
677}
678
679void UnionFuncGenerator::genFuncBody( ast::FunctionDecl * functionDecl ) {
680 const CodeLocation& location = functionDecl->location;
681 auto & params = functionDecl->params;
682 if ( InitTweak::isCopyConstructor( functionDecl )
683 || InitTweak::isAssignment( functionDecl ) ) {
684 assert( 2 == params.size() );
685 auto dstParam = params.front().strict_as<ast::ObjectDecl>();
686 auto srcParam = params.back().strict_as<ast::ObjectDecl>();
687 functionDecl->stmts = new ast::CompoundStmt( location,
688 { makeAssignOp( location, dstParam, srcParam ) }
689 );
690 } else {
691 assert( 1 == params.size() );
692 // Default constructor and destructor is empty.
693 functionDecl->stmts = new ast::CompoundStmt( location );
694 }
695}
696
697ast::ExprStmt * UnionFuncGenerator::makeAssignOp( const CodeLocation& location,
698 const ast::ObjectDecl * dstParam, const ast::ObjectDecl * srcParam ) {
699 return new ast::ExprStmt( location, new ast::UntypedExpr(
700 location,
701 new ast::NameExpr( location, "__builtin_memcpy" ),
702 {
703 new ast::AddressExpr( location,
704 new ast::VariableExpr( location, dstParam ) ),
705 // For array types, the parameter decays to a pointer, so the
706 // variable already points to the data. For other types, take &src.
707 dynamic_cast<const ast::ArrayType *>( srcParam->type.get() )
708 ? (ast::Expr *)new ast::CastExpr( location,
709 new ast::VariableExpr( location, srcParam ),
710 new ast::PointerType( new ast::VoidType() ) )
711 : (ast::Expr *)new ast::AddressExpr( location,
712 new ast::VariableExpr( location, srcParam ) ),
713 new ast::SizeofExpr( location, srcParam->type ),
714 } ) );
715}
716
717void EnumFuncGenerator::genStandardFuncs() {
718 // do everything FuncGenerator does except not make ForwardDecls
719 ast::FunctionDecl *(FuncGenerator::*standardProtos[4])() const = {
720 &EnumFuncGenerator::genCtorProto, &EnumFuncGenerator::genCopyProto,
721 &EnumFuncGenerator::genDtorProto, &EnumFuncGenerator::genAssignProto };
722
723 for ( auto & generator : standardProtos ) {
724 ast::FunctionDecl * decl = (this->*generator)();
725 genFuncBody( decl );
726 if ( CodeGen::isAssignment( decl->name ) ) {
727 appendReturnThis( decl );
728 }
729 produceDecl( decl );
730 }
731}
732
733void EnumFuncGenerator::genFieldCtors() {
734 // Enumerations to not have field constructors.
735}
736
737void EnumFuncGenerator::genFuncBody( ast::FunctionDecl * functionDecl ) {
738 const CodeLocation& location = functionDecl->location;
739 auto & params = functionDecl->params;
740 if ( InitTweak::isCopyConstructor( functionDecl )
741 || InitTweak::isAssignment( functionDecl ) ) {
742 assert( 2 == params.size() );
743 auto dstParam = params.front().strict_as<ast::ObjectDecl>();
744 auto srcParam = params.back().strict_as<ast::ObjectDecl>();
745
746 /* This looks like a recursive call, but code-gen will turn it into
747 * a C-style assignment.
748 *
749 * This is still before function pointer type conversion,
750 * so this will have to do it manually.
751 *
752 * It will also reference the parent function declaration, creating
753 * a cycle for references. This also means that the ref-counts are
754 * now non-zero and the declaration will be deleted if it ever
755 * returns to zero.
756 */
757 auto callExpr = new ast::ApplicationExpr( location,
758 ast::VariableExpr::functionPointer( location, functionDecl ),
759 {
760 new ast::VariableExpr( location, dstParam ),
761 new ast::VariableExpr( location, srcParam )
762 }
763 );
764
765 functionDecl->stmts = new ast::CompoundStmt( location,
766 { new ast::ExprStmt( location, callExpr ) }
767 );
768 } else {
769 assert( 1 == params.size() );
770 // Default constructor and destructor is empty.
771 functionDecl->stmts = new ast::CompoundStmt( location );
772 }
773}
774
775void TypeFuncGenerator::genFieldCtors() {
776 // Opaque types do not have field constructors.
777}
778
779void TypeFuncGenerator::genFuncBody( ast::FunctionDecl * functionDecl ) {
780 const CodeLocation& location = functionDecl->location;
781 auto & params = functionDecl->type->params;
782 assertf( 1 == params.size() || 2 == params.size(),
783 "Incorrect number of parameters in autogenerated typedecl function: %zd",
784 params.size() );
785 auto dstParam = params.front().strict_as<ast::ObjectDecl>();
786 auto srcParam = (2 == params.size())
787 ? params.back().strict_as<ast::ObjectDecl>() : nullptr;
788 // Generate appropriate calls to member constructor and assignment.
789 ast::UntypedExpr * expr = new ast::UntypedExpr( location,
790 new ast::NameExpr( location, functionDecl->name )
791 );
792 expr->args.push_back( new ast::CastExpr( location,
793 new ast::VariableExpr( location, dstParam ),
794 new ast::ReferenceType( decl->base )
795 ) );
796 if ( srcParam ) {
797 expr->args.push_back( new ast::CastExpr( location,
798 new ast::VariableExpr( location, srcParam ),
799 decl->base
800 ) );
801 }
802 functionDecl->stmts = new ast::CompoundStmt( location,
803 { new ast::ExprStmt( location, expr ) }
804 );
805}
806
807} // namespace
808
809void autogenerateRoutines( ast::TranslationUnit & translationUnit ) {
810 ast::Pass<AutogenerateRoutines>::run( translationUnit );
811}
812
813} // Validate
814
815// Local Variables: //
816// tab-width: 4 //
817// mode: c++ //
818// compile-command: "make install" //
819// End: //
Note: See TracBrowser for help on using the repository browser.