source: src/GenPoly/Box.cpp @ fd4df379

Last change on this file since fd4df379 was fd4df379, checked in by Michael Brooks <mlbrooks@…>, 5 days ago

Implement boxing for arrays.

The added test is things that did not work before.

  • Property mode set to 100644
File size: 84.5 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// Box.cpp -- Implement polymorphic function calls and types.
8//
9// Author           : Andrew Beach
10// Created On       : Thr Oct  6 13:39:00 2022
11// Last Modified By : Peter A. Buhr
12// Last Modified On : Thu Dec 14 17:42:17 2023
13// Update Count     : 7
14//
15
16#include "Box.hpp"
17
18#include "AST/Decl.hpp"                // for Decl, FunctionDecl, ...
19#include "AST/Expr.hpp"                // for AlignofExpr, ConstantExpr, ...
20#include "AST/Init.hpp"                // for Init, SingleInit
21#include "AST/Inspect.hpp"             // for getFunctionName
22#include "AST/Pass.hpp"                // for Pass, WithDeclsToAdd, ...
23#include "AST/Stmt.hpp"                // for CompoundStmt, ExprStmt, ...
24#include "AST/Vector.hpp"              // for vector
25#include "AST/GenericSubstitution.hpp" // for genericSubstitution
26#include "CodeGen/OperatorTable.hpp"   // for isAssignment
27#include "Common/Iterate.hpp"          // for group_iterate
28#include "Common/ScopedMap.hpp"        // for ScopedMap
29#include "Common/ToString.hpp"         // for toCString
30#include "Common/UniqueName.hpp"       // for UniqueName
31#include "GenPoly/FindFunction.hpp"    // for findFunction
32#include "GenPoly/GenPoly.hpp"         // for getFunctionType, ...
33#include "GenPoly/Lvalue.hpp"          // for generalizedLvalue
34#include "GenPoly/ScopedSet.hpp"       // for ScopedSet
35#include "GenPoly/ScrubTypeVars.hpp"   // for scrubTypeVars, scrubAllTypeVars
36#include "ResolvExpr/Unify.hpp"        // for typesCompatible
37#include "SymTab/Mangler.hpp"          // for mangle, mangleType
38
39namespace GenPoly {
40
41namespace {
42
43/// The layout type is used to represent sizes, alignments and offsets.
44ast::BasicType * makeLayoutType() {
45        return new ast::BasicType( ast::BasicKind::LongUnsignedInt );
46}
47
48/// Fixed version of layout type (just adding a 'C' in C++ style).
49ast::BasicType * makeLayoutCType() {
50        return new ast::BasicType( ast::BasicKind::LongUnsignedInt,
51                ast::CV::Qualifiers( ast::CV::Const ) );
52}
53
54// --------------------------------------------------------------------------
55/// Adds layout-generation functions to polymorphic types.
56struct LayoutFunctionBuilder final :
57                public ast::WithDeclsToAdd<>,
58                public ast::WithShortCircuiting,
59                public ast::WithVisitorRef<LayoutFunctionBuilder> {
60        void previsit( ast::StructDecl const * decl );
61        void previsit( ast::UnionDecl const * decl );
62};
63
64/// Get all sized type declarations; those that affect a layout function.
65ast::vector<ast::TypeDecl> takeSizedParams(
66                ast::vector<ast::TypeDecl> const & decls ) {
67        ast::vector<ast::TypeDecl> sizedParams;
68        for ( ast::ptr<ast::TypeDecl> const & decl : decls ) {
69                if ( decl->isComplete() ) {
70                        sizedParams.emplace_back( decl );
71                }
72        }
73        return sizedParams;
74}
75
76/// Adds parameters for otype size and alignment to a function type.
77void addSTypeParams(
78                ast::vector<ast::DeclWithType> & params,
79                ast::vector<ast::TypeDecl> const & sizedParams ) {
80        for ( ast::ptr<ast::TypeDecl> const & sizedParam : sizedParams ) {
81                ast::TypeInstType inst( sizedParam );
82                std::string paramName = Mangle::mangleType( &inst );
83                params.emplace_back( new ast::ObjectDecl(
84                        sizedParam->location,
85                        sizeofName( paramName ),
86                        makeLayoutCType()
87                ) );
88                params.emplace_back( new ast::ObjectDecl(
89                        sizedParam->location,
90                        alignofName( paramName ),
91                        makeLayoutCType()
92                ) );
93        }
94}
95
96ast::Type * makeLayoutOutType() {
97        return new ast::PointerType( makeLayoutType() );
98}
99
100struct LayoutData {
101        ast::FunctionDecl * function;
102        ast::ObjectDecl * sizeofParam;
103        ast::ObjectDecl * alignofParam;
104        ast::ObjectDecl * offsetofParam;
105};
106
107LayoutData buildLayoutFunction(
108                CodeLocation const & location, ast::AggregateDecl const * aggr,
109                ast::vector<ast::TypeDecl> const & sizedParams,
110                bool isInFunction, bool isStruct ) {
111        ast::ObjectDecl * sizeParam = new ast::ObjectDecl(
112                location,
113                sizeofName( aggr->name ),
114                makeLayoutOutType()
115        );
116        ast::ObjectDecl * alignParam = new ast::ObjectDecl(
117                location,
118                alignofName( aggr->name ),
119                makeLayoutOutType()
120        );
121        ast::ObjectDecl * offsetParam = nullptr;
122        ast::vector<ast::DeclWithType> params = { sizeParam, alignParam };
123        if ( isStruct ) {
124                offsetParam = new ast::ObjectDecl(
125                        location,
126                        offsetofName( aggr->name ),
127                        makeLayoutOutType()
128                );
129                params.push_back( offsetParam );
130        }
131        addSTypeParams( params, sizedParams );
132
133        // Routines at global scope marked "static" to prevent multiple
134        // definitions is separate translation units because each unit generates
135        // copies of the default routines for each aggregate.
136        ast::FunctionDecl * layoutDecl = new ast::FunctionDecl(
137                location,
138                layoutofName( aggr ),
139                {}, // forall
140                {}, // assertions
141                std::move( params ),
142                {}, // returns
143                new ast::CompoundStmt( location ),
144                isInFunction ? ast::Storage::Classes() : ast::Storage::Static,
145                ast::Linkage::AutoGen,
146                {}, // attrs
147                ast::Function::Inline,
148                ast::FixedArgs
149        );
150        layoutDecl->fixUniqueId();
151        return LayoutData{ layoutDecl, sizeParam, alignParam, offsetParam };
152}
153
154/// Makes a binary operation.
155ast::Expr * makeOp( CodeLocation const & location, std::string const & name,
156                ast::Expr const * lhs, ast::Expr const * rhs ) {
157        return new ast::UntypedExpr( location,
158                new ast::NameExpr( location, name ), { lhs, rhs } );
159}
160
161/// Make a binary operation and wrap it in a statement.
162ast::Stmt * makeOpStmt( CodeLocation const & location, std::string const & name,
163                ast::Expr const * lhs, ast::Expr const * rhs ) {
164        return new ast::ExprStmt( location, makeOp( location, name, lhs, rhs ) );
165}
166
167/// Returns the dereference of a local pointer variable.
168ast::Expr * derefVar(
169                CodeLocation const & location, ast::ObjectDecl const * var ) {
170        return ast::UntypedExpr::createDeref( location,
171                new ast::VariableExpr( location, var ) );
172}
173
174/// Makes an if-statement with a single-expression then and no else.
175ast::Stmt * makeCond( CodeLocation const & location,
176                ast::Expr const * cond, ast::Expr const * thenPart ) {
177        return new ast::IfStmt( location,
178                cond, new ast::ExprStmt( location, thenPart ), nullptr );
179}
180
181/// Makes a statement that aligns lhs to rhs (rhs should be an integer
182/// power of two).
183ast::Stmt * makeAlignTo( CodeLocation const & location,
184                ast::Expr const * lhs, ast::Expr const * rhs ) {
185        // Check that the lhs is zeroed out to the level of rhs.
186        ast::Expr * ifCond = makeOp( location, "?&?", lhs,
187                makeOp( location, "?-?", rhs,
188                                ast::ConstantExpr::from_ulong( location, 1 ) ) );
189        // If not aligned, increment to alignment.
190        ast::Expr * ifExpr = makeOp( location, "?+=?", ast::deepCopy( lhs ),
191                makeOp( location, "?-?", ast::deepCopy( rhs ),
192                                ast::deepCopy( ifCond ) ) );
193        return makeCond( location, ifCond, ifExpr );
194}
195
196/// Makes a statement that assigns rhs to lhs if lhs < rhs.
197ast::Stmt * makeAssignMax( CodeLocation const & location,
198                ast::Expr const * lhs, ast::Expr const * rhs ) {
199        return makeCond( location,
200                makeOp( location, "?<?", ast::deepCopy( lhs ), ast::deepCopy( rhs ) ),
201                makeOp( location, "?=?", lhs, rhs ) );
202}
203
204void LayoutFunctionBuilder::previsit( ast::StructDecl const * decl ) {
205        // Do not generate layout function for empty tag structures.
206        visit_children = false;
207        if ( decl->members.empty() ) return;
208
209        // Get parameters that can change layout, exiting early if none.
210        ast::vector<ast::TypeDecl> sizedParams =
211                takeSizedParams( decl->params );
212        if ( sizedParams.empty() ) return;
213
214        CodeLocation const & location = decl->location;
215
216        // Build layout function signature.
217        LayoutData layout = buildLayoutFunction(
218                location, decl, sizedParams, isInFunction(), true );
219        ast::FunctionDecl * layoutDecl = layout.function;
220        // Also return these or extract them from the parameter list?
221        ast::ObjectDecl const * sizeofParam = layout.sizeofParam;
222        ast::ObjectDecl const * alignofParam = layout.alignofParam;
223        ast::ObjectDecl const * offsetofParam = layout.offsetofParam;
224        assert( nullptr != layout.offsetofParam );
225
226        // Calculate structure layout in function body.
227        // Initialize size and alignment to 0 and 1
228        // (Will have at least one member to update size).
229        auto & kids = layoutDecl->stmts.get_and_mutate()->kids;
230        kids.emplace_back( makeOpStmt( location, "?=?",
231                derefVar( location, sizeofParam ),
232                ast::ConstantExpr::from_ulong( location, 0 )
233        ) );
234        kids.emplace_back( makeOpStmt( location, "?=?",
235                derefVar( location, alignofParam ),
236                ast::ConstantExpr::from_ulong( location, 1 )
237        ) );
238        // TODO: Polymorphic types will be out of the struct declaration scope.
239        // This breaks invariants until it is corrected later.
240        for ( auto const & member : enumerate( decl->members ) ) {
241                auto dwt = member.val.strict_as<ast::DeclWithType>();
242                ast::Type const * memberType = dwt->get_type();
243
244                if ( 0 < member.idx ) {
245                        // Make sure all later members have padding to align them.
246                        kids.emplace_back( makeAlignTo( location,
247                                derefVar( location, sizeofParam ),
248                                new ast::AlignofExpr( location, ast::deepCopy( memberType ) )
249                        ) );
250                }
251
252                // Place current size in the current offset index.
253                kids.emplace_back( makeOpStmt( location, "?=?",
254                        makeOp( location, "?[?]",
255                                new ast::VariableExpr( location, offsetofParam ),
256                                ast::ConstantExpr::from_ulong( location, member.idx ) ),
257                        derefVar( location, sizeofParam ) ) );
258
259                // Add member size to current size.
260                kids.emplace_back( makeOpStmt( location, "?+=?",
261                        derefVar( location, sizeofParam ),
262                        new ast::SizeofExpr( location, ast::deepCopy( memberType ) ) ) );
263
264                // Take max of member alignment and global alignment.
265                // (As align is always 2^n, this will always be a multiple of both.)
266                kids.emplace_back( makeAssignMax( location,
267                        derefVar( location, alignofParam ),
268                        new ast::AlignofExpr( location, ast::deepCopy( memberType ) ) ) );
269        }
270        // Make sure the type is end-padded to a multiple of its alignment.
271        kids.emplace_back( makeAlignTo( location,
272                derefVar( location, sizeofParam ),
273                derefVar( location, alignofParam ) ) );
274
275        declsToAddAfter.emplace_back( layoutDecl );
276}
277
278void LayoutFunctionBuilder::previsit( ast::UnionDecl const * decl ) {
279        visit_children = false;
280        // Do not generate layout function for empty tag unions.
281        if ( decl->members.empty() ) return;
282
283        // Get parameters that can change layout, exiting early if none.
284        ast::vector<ast::TypeDecl> sizedParams =
285                takeSizedParams( decl->params );
286        if ( sizedParams.empty() ) return;
287
288        CodeLocation const & location = decl->location;
289
290        // Build layout function signature.
291        LayoutData layout = buildLayoutFunction(
292                location, decl, sizedParams, isInFunction(), false );
293        ast::FunctionDecl * layoutDecl = layout.function;
294        // Also return these or extract them from the parameter list?
295        ast::ObjectDecl const * sizeofParam = layout.sizeofParam;
296        ast::ObjectDecl const * alignofParam = layout.alignofParam;
297        assert( nullptr == layout.offsetofParam );
298
299        // Calculate union layout in function body.
300        // Both are simply the maximum for union (actually align is always the
301        // LCM, but with powers of two that is also the maximum).
302        auto & kids = layoutDecl->stmts.get_and_mutate()->kids;
303        kids.emplace_back( makeOpStmt( location,
304                "?=?", derefVar( location, sizeofParam ),
305                ast::ConstantExpr::from_ulong( location, 1 )
306        ) );
307        kids.emplace_back( makeOpStmt( location,
308                "?=?", derefVar( location, alignofParam ),
309                ast::ConstantExpr::from_ulong( location, 1 )
310        ) );
311        // TODO: Polymorphic types will be out of the union declaration scope.
312        // This breaks invariants until it is corrected later.
313        for ( auto const & member : decl->members ) {
314                auto dwt = member.strict_as<ast::DeclWithType>();
315                ast::Type const * memberType = dwt->get_type();
316
317                // Take max member size and global size.
318                kids.emplace_back( makeAssignMax( location,
319                        derefVar( location, sizeofParam ),
320                        new ast::SizeofExpr( location, ast::deepCopy( memberType ) )
321                ) );
322
323                // Take max of member alignment and global alignment.
324                kids.emplace_back( makeAssignMax( location,
325                        derefVar( location, alignofParam ),
326                        new ast::AlignofExpr( location, ast::deepCopy( memberType ) )
327                ) );
328        }
329        kids.emplace_back( makeAlignTo( location,
330                derefVar( location, sizeofParam ),
331                derefVar( location, alignofParam ) ) );
332
333        declsToAddAfter.emplace_back( layoutDecl );
334}
335
336// --------------------------------------------------------------------------
337/// Application expression transformer.
338/// * Replaces polymorphic return types with out-parameters.
339/// * Replaces call to polymorphic functions with adapter calls which handles
340///   dynamic arguments and return values.
341/// * Adds appropriate type variables to the function calls.
342struct CallAdapter final :
343                public ast::WithConstTypeSubstitution,
344                public ast::WithGuards,
345                public ast::WithShortCircuiting,
346                public ast::WithStmtsToAdd<>,
347                public ast::WithVisitorRef<CallAdapter> {
348        CallAdapter();
349
350        void previsit( ast::Decl const * decl );
351        ast::FunctionDecl const * previsit( ast::FunctionDecl const * decl );
352        void previsit( ast::TypeDecl const * decl );
353        void previsit( ast::CommaExpr const * expr );
354        ast::Expr const * postvisit( ast::ApplicationExpr const * expr );
355        ast::Expr const * postvisit( ast::UntypedExpr const * expr );
356        void previsit( ast::AddressExpr const * expr );
357        ast::Expr const * postvisit( ast::AddressExpr const * expr );
358        ast::ReturnStmt const * previsit( ast::ReturnStmt const * stmt );
359
360        void beginScope();
361        void endScope();
362private:
363        // Many helpers here use a mutable ApplicationExpr as an in/out parameter
364        // instead of using the return value, to save on mutates and free up the
365        // return value.
366
367        /// Passes extra layout arguments for sized polymorphic type parameters.
368        void passTypeVars(
369                ast::ApplicationExpr * expr,
370                ast::vector<ast::Expr> & extraArgs,
371                ast::FunctionType const * funcType );
372        /// Wraps a function application with a new temporary for the
373        /// out-parameter return value.
374        ast::Expr const * addRetParam(
375                ast::ApplicationExpr * expr, ast::Type const * retType );
376        /// Wraps a function application returning a polymorphic type with a new
377        /// temporary for the out-parameter return value.
378        ast::Expr const * addDynRetParam(
379                ast::ApplicationExpr * expr, ast::Type const * polyType );
380        /// Modify a call so it passes the function through the correct adapter.
381        ast::Expr const * applyAdapter(
382                ast::ApplicationExpr * expr,
383                ast::FunctionType const * function );
384        /// Convert a single argument into its boxed form to pass the parameter.
385        void boxParam( ast::ptr<ast::Expr> & arg,
386                ast::Type const * formal, TypeVarMap const & exprTyVars );
387        /// Box every argument from arg forward, matching the functionType
388        /// parameter list. arg should point into expr's argument list.
389        void boxParams(
390                ast::ApplicationExpr * expr,
391                ast::Type const * polyRetType,
392                ast::FunctionType const * function,
393                const TypeVarMap & typeVars );
394        /// Adds the inferred parameters derived from the assertions of the
395        /// expression to the call.
396        void addInferredParams(
397                ast::ApplicationExpr * expr,
398                ast::vector<ast::Expr> & extraArgs,
399                ast::FunctionType const * functionType,
400                const TypeVarMap & typeVars );
401        /// Stores assignment operators from assertion list in
402        /// local map of assignment operations.
403        void passAdapters(
404                ast::ApplicationExpr * expr,
405                ast::FunctionType const * type,
406                const TypeVarMap & typeVars );
407        /// Create an adapter function based on the type of the adaptee and the
408        /// real type with the type substitutions applied.
409        ast::FunctionDecl * makeAdapter(
410                ast::FunctionType const * adaptee,
411                ast::FunctionType const * realType,
412                std::string const & mangleName,
413                TypeVarMap const & typeVars,
414                CodeLocation const & location ) const;
415        /// Replaces intrinsic operator functions with their arithmetic desugaring.
416        ast::Expr const * handleIntrinsics( ast::ApplicationExpr const * );
417        /// Inserts a new temporary variable into the current scope with an
418        /// auto-generated name.
419        ast::ObjectDecl * makeTemporary(
420                CodeLocation const & location, ast::Type const * type );
421
422        TypeVarMap scopeTypeVars;
423        ScopedMap< std::string, ast::DeclWithType const * > adapters;
424        std::map< ast::ApplicationExpr const *, ast::Expr const * > retVals;
425        ast::DeclWithType const * retval;
426        UniqueName tmpNamer;
427};
428
429/// Replaces a polymorphic type with its concrete equivalant under the
430/// current environment (returns itself if concrete).
431/// If `doClone` is set to false, will not clone interior types
432ast::Type const * replaceWithConcrete(
433                ast::Type const * type,
434                ast::TypeSubstitution const & typeSubs,
435                bool doCopy = true );
436
437/// Replaces all the type parameters of a generic type with their
438/// concrete equivalents under the current environment.
439void replaceParametersWithConcrete(
440                ast::vector<ast::Expr> & params,
441                ast::TypeSubstitution const & typeSubs ) {
442        for ( ast::ptr<ast::Expr> & paramExpr : params ) {
443                ast::TypeExpr const * param = paramExpr.as<ast::TypeExpr>();
444                assertf( param, "Aggregate parameters should be type expressions." );
445                paramExpr = ast::mutate_field( param, &ast::TypeExpr::type,
446                        replaceWithConcrete( param->type.get(), typeSubs, false ) );
447        }
448}
449
450ast::Type const * replaceWithConcrete(
451                ast::Type const * type,
452                ast::TypeSubstitution const & typeSubs,
453                bool doCopy ) {
454        if ( auto instType = dynamic_cast<ast::TypeInstType const *>( type ) ) {
455                ast::Type const * concrete = typeSubs.lookup( instType );
456                return ( nullptr != concrete ) ? concrete : instType;
457        } else if ( auto structType =
458                        dynamic_cast<ast::StructInstType const *>( type ) ) {
459                ast::StructInstType * newType =
460                        doCopy ? ast::deepCopy( structType ) : ast::mutate( structType );
461                replaceParametersWithConcrete( newType->params, typeSubs );
462                return newType;
463        } else if ( auto unionType =
464                        dynamic_cast<ast::UnionInstType const *>( type ) ) {
465                ast::UnionInstType * newType =
466                        doCopy ? ast::deepCopy( unionType ) : ast::mutate( unionType );
467                replaceParametersWithConcrete( newType->params, typeSubs );
468                return newType;
469        } else {
470                return type;
471        }
472}
473
474std::string makePolyMonoSuffix(
475                ast::FunctionType const * function,
476                TypeVarMap const & typeVars ) {
477        // If the return type or a parameter type involved polymorphic types,
478        // then the adapter will need to take those polymorphic types as pointers.
479        // Therefore, there can be two different functions with the same mangled
480        // name, so we need to further mangle the names.
481        std::stringstream name;
482        for ( auto ret : function->returns ) {
483                name << ( isPolyType( ret, typeVars ) ? 'P' : 'M' );
484        }
485        name << '_';
486        for ( auto arg : function->params ) {
487                name << ( isPolyType( arg, typeVars ) ? 'P' : 'M' );
488        }
489        return name.str();
490}
491
492std::string mangleAdapterName(
493                ast::FunctionType const * function,
494                TypeVarMap const & typeVars ) {
495        return Mangle::mangle( function, {} )
496                + makePolyMonoSuffix( function, typeVars );
497}
498
499std::string makeAdapterName( std::string const & mangleName ) {
500        return "_adapter" + mangleName;
501}
502
503void makeRetParam( ast::FunctionType * type ) {
504        ast::ptr<ast::Type> & retParam = type->returns.front();
505
506        // Make a new parameter that is a pointer to the type of the old return value.
507        retParam = new ast::PointerType( retParam.get() );
508        type->params.emplace( type->params.begin(), retParam );
509
510        // We don't need the return value any more.
511        type->returns.clear();
512}
513
514ast::FunctionType * makeAdapterType(
515                ast::FunctionType const * adaptee,
516                TypeVarMap const & typeVars ) {
517        ast::FunctionType * adapter = ast::deepCopy( adaptee );
518        if ( isDynRet( adapter, typeVars ) ) {
519                makeRetParam( adapter );
520        }
521        adapter->params.emplace( adapter->params.begin(),
522                new ast::PointerType( new ast::FunctionType( ast::VariableArgs ) )
523        );
524        return adapter;
525}
526
527CallAdapter::CallAdapter() : tmpNamer( "_temp" ) {}
528
529void CallAdapter::previsit( ast::Decl const * ) {
530        // Prevent type declaration information from leaking out.
531        GuardScope( scopeTypeVars );
532}
533
534ast::FunctionDecl const * CallAdapter::previsit( ast::FunctionDecl const * decl ) {
535        // Prevent type declaration information from leaking out.
536        GuardScope( scopeTypeVars );
537
538        if ( nullptr == decl->stmts ) {
539                return decl;
540        }
541
542        GuardValue( retval );
543
544        // Process polymorphic return value.
545        retval = nullptr;
546        ast::FunctionType const * type = decl->type;
547        if ( isDynRet( type ) && decl->linkage != ast::Linkage::C ) {
548                retval = decl->returns.front();
549
550                // Give names to unnamed return values.
551                if ( "" == retval->name ) {
552                        auto mutRet = ast::mutate( retval );
553                        mutRet->name = "_retparam";
554                        mutRet->linkage = ast::Linkage::C;
555                        retval = mutRet;
556                        decl = ast::mutate_field_index( decl,
557                                &ast::FunctionDecl::returns, 0, mutRet );
558                }
559        }
560
561        // The formal_usage/expr_id values may be off if we get them from the
562        // type, trying the declaration instead.
563        makeTypeVarMap( type, scopeTypeVars );
564
565        // Get all needed adapters from the call. We will forward them.
566        ast::vector<ast::FunctionType> functions;
567        for ( ast::ptr<ast::VariableExpr> const & assertion : type->assertions ) {
568                auto atype = assertion->result.get();
569                findFunction( atype, functions, scopeTypeVars, needsAdapter );
570        }
571
572        for ( ast::ptr<ast::Type> const & arg : type->params ) {
573                findFunction( arg, functions, scopeTypeVars, needsAdapter );
574        }
575
576        for ( auto funcType : functions ) {
577                std::string mangleName = mangleAdapterName( funcType, scopeTypeVars );
578                if ( adapters.contains( mangleName ) ) continue;
579                std::string adapterName = makeAdapterName( mangleName );
580                // NODE: This creates floating nodes, breaking invariants.
581                // This is corrected in the RewireAdapters sub-pass.
582                adapters.insert(
583                        mangleName,
584                        new ast::ObjectDecl(
585                                decl->location,
586                                adapterName,
587                                new ast::PointerType(
588                                        makeAdapterType( funcType, scopeTypeVars ) ),
589                                nullptr, // init
590                                ast::Storage::Classes(),
591                                ast::Linkage::C
592                        )
593                );
594        }
595
596        return decl;
597}
598
599void CallAdapter::previsit( ast::TypeDecl const * decl ) {
600        addToTypeVarMap( decl, scopeTypeVars );
601}
602
603void CallAdapter::previsit( ast::CommaExpr const * expr ) {
604        // Attempting to find application expressions that were mutated by the
605        // copy constructor passes to use an explicit return variable, so that
606        // the variable can be reused as a parameter to the call rather than
607        // creating a new temporary variable. Previously this step was an
608        // optimization, but with the introduction of tuples and UniqueExprs,
609        // it is necessary to ensure that they use the same variable.
610        // Essentially, looking for pattern:
611        // (x=f(...), x)
612        // To compound the issue, the right side can be *x, etc.
613        // because of lvalue-returning functions
614        if ( auto assign = expr->arg1.as<ast::UntypedExpr>() ) {
615                if ( CodeGen::isAssignment( ast::getFunctionName( assign ) ) ) {
616                        assert( 2 == assign->args.size() );
617                        if ( auto app = assign->args.back().as<ast::ApplicationExpr>() ) {
618                                // First argument is assignable, so it must be an lvalue,
619                                // so it should be legal to takes its address.
620                                retVals.insert_or_assign( app, assign->args.front() );
621                        }
622                }
623        }
624}
625
626ast::Expr const * CallAdapter::postvisit( ast::ApplicationExpr const * expr ) {
627        assert( expr->func->result );
628        ast::FunctionType const * function = getFunctionType( expr->func->result );
629        assertf( function, "ApplicationExpr has non-function type %s",
630                        toCString( expr->func->result ) );
631
632        if ( auto newExpr = handleIntrinsics( expr ) ) {
633                return newExpr;
634        }
635
636        ast::ApplicationExpr * mutExpr = ast::mutate( expr );
637        ast::Expr const * ret = expr;
638
639        TypeVarMap exprTypeVars;
640        makeTypeVarMap( function, exprTypeVars );
641        auto dynRetType = isDynRet( function, exprTypeVars );
642
643        // NOTE: addDynRetParam needs to know the actual (generated) return type
644        // so it can make a temporary variable, so pass the result type form the
645        // `expr` `passTypeVars` needs to know the program-text return type ([ex]
646        // the distinction between _conc_T30 and T3(int)) concRetType may not be
647        // a good name in one or both of these places.
648        if ( dynRetType ) {
649                ast::Type const * result = mutExpr->result;
650                ast::Type const * concRetType = result->isVoid() ? nullptr : result;
651                // [Comment from before translation.]
652                // Used to use dynRetType instead of concRetType.
653                ret = addDynRetParam( mutExpr, concRetType );
654        } else if ( needsAdapter( function, scopeTypeVars )
655                        && !needsAdapter( function, exprTypeVars ) ) {
656                // Change the application so it calls the adapter rather than the
657                // passed function.
658                ret = applyAdapter( mutExpr, function );
659        }
660
661        ast::vector<ast::Expr> prependArgs;
662        passTypeVars( mutExpr, prependArgs, function );
663        addInferredParams( mutExpr, prependArgs, function, exprTypeVars );
664
665        boxParams( mutExpr, dynRetType, function, exprTypeVars );
666        spliceBegin( mutExpr->args, prependArgs );
667        passAdapters( mutExpr, function, exprTypeVars );
668
669        return ret;
670}
671
672bool isPolyDeref( ast::UntypedExpr const * expr,
673                TypeVarMap const & typeVars,
674                ast::TypeSubstitution const * typeSubs ) {
675        if ( auto name = expr->func.as<ast::NameExpr>() ) {
676                if ( "*?" == name->name ) {
677                        // It's a deref.
678                        // Must look under the * (and strip its ptr-ty) because expr's
679                        // result could be ar/ptr-decayed.  If expr.inner:T(*)[n], then
680                        // expr is a poly deref, even though expr:T*, which is not poly.
681                        auto ptrExpr = expr->args.front();
682                        auto ptrTy = ptrExpr->result.as<ast::PointerType>();
683                        assert(ptrTy); // thing being deref'd must be pointer
684                        auto referentTy = ptrTy->base;
685                        assert(referentTy);
686                        return isPolyType( referentTy, typeVars, typeSubs );
687                }
688        }
689        return false;
690}
691
692ast::Expr const * CallAdapter::postvisit( ast::UntypedExpr const * expr ) {
693        if ( isPolyDeref( expr, scopeTypeVars, typeSubs ) ) {
694                return expr->args.front();
695        }
696        return expr;
697}
698
699void CallAdapter::previsit( ast::AddressExpr const * ) {
700        visit_children = false;
701}
702
703ast::Expr const * CallAdapter::postvisit( ast::AddressExpr const * expr ) {
704        assert( expr->arg->result );
705        assert( !expr->arg->result->isVoid() );
706
707        bool doesNeedAdapter = false;
708        if ( auto un = expr->arg.as<ast::UntypedExpr>() ) {
709                if ( isPolyDeref( un, scopeTypeVars, typeSubs ) ) {
710                        if ( auto app = un->args.front().as<ast::ApplicationExpr>() ) {
711                                assert( app->func->result );
712                                auto function = getFunctionType( app->func->result );
713                                assert( function );
714                                doesNeedAdapter = needsAdapter( function, scopeTypeVars );
715                        }
716                }
717        }
718        // isPolyType check needs to happen before mutating expr arg,
719        // so pull it forward out of the if condition.
720        expr = ast::mutate_field( expr, &ast::AddressExpr::arg,
721                        expr->arg->accept( *visitor ) );
722        // But must happen after mutate, since argument might change
723        // (ex. intrinsic *?, ?[?]) re-evaluate above comment.
724        bool polyType = isPolyType( expr->arg->result, scopeTypeVars, typeSubs );
725        if ( polyType || doesNeedAdapter ) {
726                ast::Expr * ret = ast::mutate( expr->arg.get() );
727                ret->result = ast::deepCopy( expr->result );
728                return ret;
729        } else {
730                return expr;
731        }
732}
733
734ast::ReturnStmt const * CallAdapter::previsit( ast::ReturnStmt const * stmt ) {
735        // Since retval is set when the return type is dynamic, this function
736        // should have been converted to void return & out parameter.
737        if ( retval && stmt->expr ) {
738                assert( stmt->expr->result );
739                assert( !stmt->expr->result->isVoid() );
740                return ast::mutate_field( stmt, &ast::ReturnStmt::expr, nullptr );
741        }
742        return stmt;
743}
744
745void CallAdapter::beginScope() {
746        adapters.beginScope();
747}
748
749void CallAdapter::endScope() {
750        adapters.endScope();
751}
752
753/// Find instances of polymorphic type parameters.
754struct PolyFinder {
755        TypeVarMap const & typeVars;
756        bool result = false;
757        PolyFinder( TypeVarMap const & tvs ) : typeVars( tvs ) {}
758
759        void previsit( ast::TypeInstType const * type ) {
760                if ( isPolyType( type, typeVars ) ) result = true;
761        }
762};
763
764/// True if these is an instance of a polymorphic type parameter in the type.
765bool hasPolymorphism( ast::Type const * type, TypeVarMap const & typeVars ) {
766        return ast::Pass<PolyFinder>::read( type, typeVars );
767}
768
769void CallAdapter::passTypeVars(
770                ast::ApplicationExpr * expr,
771                ast::vector<ast::Expr> & extraArgs,
772                ast::FunctionType const * function ) {
773        assert( typeSubs );
774        // Pass size/align for type variables.
775        for ( ast::ptr<ast::TypeInstType> const & typeVar : function->forall ) {
776                if ( !typeVar->base->isComplete() ) continue;
777                ast::Type const * concrete = typeSubs->lookup( typeVar );
778                if ( !concrete ) {
779                        // Should this be an assertion?
780                        SemanticError( expr->location, "\nunbound type variable %s in application %s",
781                                                   toString( typeSubs ).c_str(), typeVar->typeString().c_str() );
782                }
783                extraArgs.emplace_back(
784                        new ast::SizeofExpr( expr->location, ast::deepCopy( concrete ) ) );
785                extraArgs.emplace_back(
786                        new ast::AlignofExpr( expr->location, ast::deepCopy( concrete ) ) );
787        }
788}
789
790ast::Expr const * CallAdapter::addRetParam(
791                ast::ApplicationExpr * expr, ast::Type const * retType ) {
792        // Create temporary to hold return value of polymorphic function and
793        // produce that temporary as a result using a comma expression.
794        assert( retType );
795
796        ast::Expr * paramExpr = nullptr;
797        // Try to use existing return value parameter if it exists,
798        // otherwise create a new temporary.
799        if ( retVals.count( expr ) ) {
800                paramExpr = ast::deepCopy( retVals[ expr ] );
801        } else {
802                auto newObj = makeTemporary( expr->location, ast::deepCopy( retType ) );
803                paramExpr = new ast::VariableExpr( expr->location, newObj );
804        }
805        ast::Expr * retExpr = ast::deepCopy( paramExpr );
806
807        // If the type of the temporary is not polpmorphic, box temporary by
808        // taking its address; otherwise the temporary is already boxed and can
809        // be used directly.
810        if ( !isPolyType( paramExpr->result, scopeTypeVars, typeSubs ) ) {
811                paramExpr = new ast::AddressExpr( paramExpr->location, paramExpr );
812        }
813        // Add argument to function call.
814        expr->args.insert( expr->args.begin(), paramExpr );
815        // Build a comma expression to call the function and return a value.
816        ast::CommaExpr * comma = new ast::CommaExpr(
817                expr->location, expr, retExpr );
818        comma->env = expr->env;
819        expr->env = nullptr;
820        return comma;
821}
822
823ast::Expr const * CallAdapter::addDynRetParam(
824                ast::ApplicationExpr * expr, ast::Type const * polyType ) {
825        assert( typeSubs );
826        ast::Type const * concrete = replaceWithConcrete( polyType, *typeSubs );
827        // Add out-parameter for return value.
828        return addRetParam( expr, concrete );
829}
830
831ast::Expr const * CallAdapter::applyAdapter(
832                ast::ApplicationExpr * expr,
833                ast::FunctionType const * function ) {
834        ast::Expr const * ret = expr;
835        if ( isDynRet( function, scopeTypeVars ) ) {
836                ret = addRetParam( expr, function->returns.front() );
837        }
838        std::string mangleName = mangleAdapterName( function, scopeTypeVars );
839        std::string adapterName = makeAdapterName( mangleName );
840
841        // Cast adaptee to `void (*)()`, since it may have any type inside a
842        // polymorphic function.
843        ast::Type const * adapteeType = new ast::PointerType(
844                new ast::FunctionType( ast::VariableArgs ) );
845        expr->args.insert( expr->args.begin(),
846                new ast::CastExpr( expr->location, expr->func, adapteeType ) );
847        // The result field is never set on NameExpr. / Now it is.
848        auto head = new ast::NameExpr( expr->location, adapterName );
849        head->result = ast::deepCopy( adapteeType );
850        expr->func = head;
851
852        return ret;
853}
854
855/// Cast parameters to polymorphic functions so that types are replaced with
856/// `void *` if they are type parameters in the formal type.
857/// This gets rid of warnings from gcc.
858void addCast(
859                ast::ptr<ast::Expr> & actual,
860                ast::Type const * formal,
861                TypeVarMap const & typeVars ) {
862        // Type contains polymorphism, but isn't exactly a polytype, in which
863        // case it has some real actual type (ex. unsigned int) and casting to
864        // `void *` is wrong.
865        if ( hasPolymorphism( formal, typeVars )
866                        && !isPolyType( formal, typeVars ) ) {
867                ast::Type const * newType = ast::deepCopy( formal );
868                newType = scrubTypeVars( newType, typeVars );
869                actual = new ast::CastExpr( actual->location, actual, newType );
870        }
871}
872
873void CallAdapter::boxParam( ast::ptr<ast::Expr> & arg,
874                ast::Type const * param, TypeVarMap const & exprTypeVars ) {
875        assertf( arg->result, "arg does not have result: %s", toCString( arg ) );
876        addCast( arg, param, exprTypeVars );
877        if ( !needsBoxing( param, arg->result, exprTypeVars, typeSubs ) ) {
878                return;
879        }
880        CodeLocation const & location = arg->location;
881
882        if ( arg->get_lvalue() ) {
883                // The argument expression may be CFA lvalue, but not C lvalue,
884                // so apply generalizedLvalue transformations.
885                // if ( auto var = dynamic_cast<ast::VariableExpr const *>( arg ) ) {
886                //  if ( dynamic_cast<ast::ArrayType const *>( varExpr->var->get_type() ) ){
887                //      // temporary hack - don't box arrays, because &arr is not the same as &arr[0]
888                //      return;
889                //  }
890                // }
891                arg = generalizedLvalue( new ast::AddressExpr( arg->location, arg ) );
892                if ( !ResolvExpr::typesCompatible( param, arg->result ) ) {
893                        // Silence warnings by casting boxed parameters when the actually
894                        // type does not match up with the formal type.
895                        arg = new ast::CastExpr( location, arg, ast::deepCopy( param ) );
896                }
897        } else {
898                // Use type computed in unification to declare boxed variables.
899                ast::ptr<ast::Type> newType = ast::deepCopy( param );
900                if ( typeSubs ) typeSubs->apply( newType );
901                ast::ObjectDecl * newObj = makeTemporary( location, newType );
902                auto assign = ast::UntypedExpr::createCall( location, "?=?", {
903                        new ast::VariableExpr( location, newObj ),
904                        arg,
905                } );
906                stmtsToAddBefore.push_back( new ast::ExprStmt( location, assign ) );
907                arg = new ast::AddressExpr(
908                        new ast::VariableExpr( location, newObj ) );
909        }
910}
911
912void CallAdapter::boxParams(
913                ast::ApplicationExpr * expr,
914                ast::Type const * polyRetType,
915                ast::FunctionType const * function,
916                const TypeVarMap & typeVars ) {
917        // Start at the beginning, but the return argument may have been added.
918        auto arg = expr->args.begin();
919        if ( polyRetType ) ++arg;
920
921        for ( auto param : function->params ) {
922                assertf( arg != expr->args.end(),
923                        "boxParams: missing argument for param %s to %s in %s",
924                        toCString( param ), toCString( function ), toCString( expr ) );
925                boxParam( *arg, param, typeVars );
926                ++arg;
927        }
928}
929
930void CallAdapter::addInferredParams(
931                ast::ApplicationExpr * expr,
932                ast::vector<ast::Expr> & extraArgs,
933                ast::FunctionType const * functionType,
934                TypeVarMap const & typeVars ) {
935        for ( auto assertion : functionType->assertions ) {
936                auto inferParam = expr->inferred.inferParams().find(
937                        assertion->var->uniqueId );
938                assertf( inferParam != expr->inferred.inferParams().end(),
939                        "addInferredParams missing inferred parameter: %s in: %s",
940                        toCString( assertion ), toCString( expr ) );
941                ast::ptr<ast::Expr> newExpr = ast::deepCopy( inferParam->second.expr );
942                boxParam( newExpr, assertion->result, typeVars );
943                extraArgs.emplace_back( newExpr.release() );
944        }
945}
946
947/// Modifies the ApplicationExpr to accept adapter functions for its
948/// assertion and parameters, declares the required adapters.
949void CallAdapter::passAdapters(
950                ast::ApplicationExpr * expr,
951                ast::FunctionType const * type,
952                const TypeVarMap & exprTypeVars ) {
953        // Collect a list of function types passed as parameters or implicit
954        // parameters (assertions).
955        ast::vector<ast::Type> const & paramList = type->params;
956        ast::vector<ast::FunctionType> functions;
957
958        for ( ast::ptr<ast::VariableExpr> const & assertion : type->assertions ) {
959                findFunction( assertion->result, functions, exprTypeVars, needsAdapter );
960        }
961        for ( ast::ptr<ast::Type> const & arg : paramList ) {
962                findFunction( arg, functions, exprTypeVars, needsAdapter );
963        }
964
965        // Parameter function types for which an appropriate adapter has been
966        // generated. We cannot use the types after applying substitutions,
967        // since two different parameter types may be unified to the same type.
968        std::set<std::string> adaptersDone;
969
970        CodeLocation const & location = expr->location;
971
972        for ( ast::ptr<ast::FunctionType> const & funcType : functions ) {
973                std::string mangleName = Mangle::mangle( funcType );
974
975                // Only attempt to create an adapter or pass one as a parameter if we
976                // haven't already done so for this pre-substitution parameter
977                // function type.
978                // The second part of the result if is if the element was inserted.
979                if ( !adaptersDone.insert( mangleName ).second ) continue;
980
981                // Apply substitution to type variables to figure out what the
982                // adapter's type should look like. (Copy to make the release safe.)
983                assert( typeSubs );
984                auto result = typeSubs->apply( ast::deepCopy( funcType ) );
985                ast::FunctionType * realType = ast::mutate( result.node.release() );
986                mangleName = Mangle::mangle( realType );
987                mangleName += makePolyMonoSuffix( funcType, exprTypeVars );
988
989                // Check if the adapter has already been created, or has to be.
990                using AdapterIter = decltype(adapters)::iterator;
991                AdapterIter adapter = adapters.find( mangleName );
992                if ( adapter == adapters.end() ) {
993                        ast::FunctionDecl * newAdapter = makeAdapter(
994                                funcType, realType, mangleName, exprTypeVars, location );
995                        std::pair<AdapterIter, bool> answer =
996                                adapters.insert( mangleName, newAdapter );
997                        adapter = answer.first;
998                        stmtsToAddBefore.push_back(
999                                new ast::DeclStmt( location, newAdapter ) );
1000                }
1001                assert( adapter != adapters.end() );
1002
1003                // Add the approprate adapter as a parameter.
1004                expr->args.insert( expr->args.begin(),
1005                        new ast::VariableExpr( location, adapter->second ) );
1006        }
1007}
1008
1009// Parameter and argument may be used wrong around here.
1010ast::Expr * makeAdapterArg(
1011                ast::DeclWithType const * param,
1012                ast::Type const * arg,
1013                ast::Type const * realParam,
1014                TypeVarMap const & typeVars,
1015                CodeLocation const & location ) {
1016        assert( param );
1017        assert( arg );
1018        assert( realParam );
1019        if ( isPolyType( realParam, typeVars ) && !isPolyType( arg ) ) {
1020                ast::UntypedExpr * deref = ast::UntypedExpr::createDeref(
1021                        location,
1022                        new ast::CastExpr( location,
1023                                new ast::VariableExpr( location, param ),
1024                                new ast::PointerType( ast::deepCopy( arg ) )
1025                        )
1026                );
1027                deref->result = ast::deepCopy( arg );
1028                return deref;
1029        }
1030        return new ast::VariableExpr( location, param );
1031}
1032
1033// This seems to be one of the problematic functions.
1034void addAdapterParams(
1035                ast::ApplicationExpr * adaptee,
1036                ast::vector<ast::Type>::const_iterator arg,
1037                ast::vector<ast::DeclWithType>::iterator param,
1038                ast::vector<ast::DeclWithType>::iterator paramEnd,
1039                ast::vector<ast::Type>::const_iterator realParam,
1040                TypeVarMap const & typeVars,
1041                CodeLocation const & location ) {
1042        UniqueName paramNamer( "_p" );
1043        for ( ; param != paramEnd ; ++param, ++arg, ++realParam ) {
1044                if ( "" == (*param)->name ) {
1045                        auto mutParam = (*param).get_and_mutate();
1046                        mutParam->name = paramNamer.newName();
1047                        mutParam->linkage = ast::Linkage::C;
1048                }
1049                adaptee->args.push_back(
1050                        makeAdapterArg( *param, *arg, *realParam, typeVars, location ) );
1051        }
1052}
1053
1054ast::FunctionDecl * CallAdapter::makeAdapter(
1055                ast::FunctionType const * adaptee,
1056                ast::FunctionType const * realType,
1057                std::string const & mangleName,
1058                TypeVarMap const & typeVars,
1059                CodeLocation const & location ) const {
1060        ast::FunctionType * adapterType = makeAdapterType( adaptee, typeVars );
1061        adapterType = ast::mutate( scrubTypeVars( adapterType, typeVars ) );
1062
1063        // Some of these names will be overwritten, but it gives a default.
1064        UniqueName pNamer( "_param" );
1065        UniqueName rNamer( "_ret" );
1066
1067        bool first = true;
1068
1069        ast::FunctionDecl * adapterDecl = new ast::FunctionDecl( location,
1070                makeAdapterName( mangleName ),
1071                {}, // forall
1072                {}, // assertions
1073                map_range<ast::vector<ast::DeclWithType>>( adapterType->params,
1074                                [&pNamer, &location, &first]( ast::ptr<ast::Type> const & param ) {
1075                        // [Trying to make the generated code match exactly more often.]
1076                        if ( first ) {
1077                                first = false;
1078                                return new ast::ObjectDecl( location, "_adaptee", param );
1079                        }
1080                        return new ast::ObjectDecl( location, pNamer.newName(), param );
1081                } ),
1082                map_range<ast::vector<ast::DeclWithType>>( adapterType->returns,
1083                                [&rNamer, &location]( ast::ptr<ast::Type> const & retval ) {
1084                        return new ast::ObjectDecl( location, rNamer.newName(), retval );
1085                } ),
1086                nullptr, // stmts
1087                {}, // storage
1088                ast::Linkage::C
1089        );
1090
1091        ast::DeclWithType * adapteeDecl =
1092                adapterDecl->params.front().get_and_mutate();
1093        adapteeDecl->name = "_adaptee";
1094
1095        // Do not carry over attributes to real type parameters/return values.
1096        auto mutRealType = ast::mutate( realType );
1097        for ( ast::ptr<ast::Type> & decl : mutRealType->params ) {
1098                if ( decl->attributes.empty() ) continue;
1099                auto mut = ast::mutate( decl.get() );
1100                mut->attributes.clear();
1101                decl = mut;
1102        }
1103        for ( ast::ptr<ast::Type> & decl : mutRealType->returns ) {
1104                if ( decl->attributes.empty() ) continue;
1105                auto mut = ast::mutate( decl.get() );
1106                mut->attributes.clear();
1107                decl = mut;
1108        }
1109        realType = mutRealType;
1110
1111        ast::ApplicationExpr * adapteeApp = new ast::ApplicationExpr( location,
1112                new ast::CastExpr( location,
1113                        new ast::VariableExpr( location, adapteeDecl ),
1114                        new ast::PointerType( realType )
1115                )
1116        );
1117
1118        for ( auto const & [assertArg, assertParam, assertReal] : group_iterate(
1119                        realType->assertions, adapterType->assertions, adaptee->assertions ) ) {
1120                adapteeApp->args.push_back( makeAdapterArg(
1121                        assertParam->var, assertArg->var->get_type(),
1122                        assertReal->var->get_type(), typeVars, location
1123                ) );
1124        }
1125
1126        ast::vector<ast::Type>::const_iterator
1127                arg = realType->params.begin(),
1128                param = adapterType->params.begin(),
1129                realParam = adaptee->params.begin();
1130        ast::vector<ast::DeclWithType>::iterator
1131                paramDecl = adapterDecl->params.begin();
1132        // Skip adaptee parameter in the adapter type.
1133        ++param;
1134        ++paramDecl;
1135
1136        ast::Stmt * bodyStmt;
1137        // Returns void/nothing.
1138        if ( realType->returns.empty() ) {
1139                addAdapterParams( adapteeApp, arg, paramDecl, adapterDecl->params.end(),
1140                        realParam, typeVars, location );
1141                bodyStmt = new ast::ExprStmt( location, adapteeApp );
1142        // Returns a polymorphic type.
1143        } else if ( isDynType( adaptee->returns.front(), typeVars ) ) {
1144                ast::UntypedExpr * assign = new ast::UntypedExpr( location,
1145                        new ast::NameExpr( location, "?=?" ) );
1146                ast::UntypedExpr * deref = ast::UntypedExpr::createDeref( location,
1147                        new ast::CastExpr( location,
1148                                new ast::VariableExpr( location, *paramDecl++ ),
1149                                new ast::PointerType(
1150                                        ast::deepCopy( realType->returns.front() ) ) ) );
1151                assign->args.push_back( deref );
1152                addAdapterParams( adapteeApp, arg, paramDecl, adapterDecl->params.end(),
1153                        realParam, typeVars, location );
1154                assign->args.push_back( adapteeApp );
1155                bodyStmt = new ast::ExprStmt( location, assign );
1156        // Adapter for a function that returns a monomorphic value.
1157        } else {
1158                addAdapterParams( adapteeApp, arg, paramDecl, adapterDecl->params.end(),
1159                                realParam, typeVars, location );
1160                bodyStmt = new ast::ReturnStmt( location, adapteeApp );
1161        }
1162
1163        adapterDecl->stmts = new ast::CompoundStmt( location, { bodyStmt } );
1164        return adapterDecl;
1165}
1166
1167ast::Expr const * makeIncrDecrExpr(
1168                CodeLocation const & location,
1169                ast::ApplicationExpr const * expr,
1170                ast::Type const * polyType,
1171                bool isIncr ) {
1172        ast::NameExpr * opExpr =
1173                        new ast::NameExpr( location, isIncr ? "?+=?" : "?-=?" );
1174        ast::UntypedExpr * addAssign = new ast::UntypedExpr( location, opExpr );
1175        if ( auto address = expr->args.front().as<ast::AddressExpr>() ) {
1176                addAssign->args.push_back( address->arg );
1177        } else {
1178                addAssign->args.push_back( expr->args.front() );
1179        }
1180        addAssign->args.push_back( new ast::NameExpr( location,
1181                sizeofName( Mangle::mangleType( polyType ) ) ) );
1182        addAssign->result = ast::deepCopy( expr->result );
1183        addAssign->env = expr->env ? expr->env : addAssign->env;
1184        return addAssign;
1185}
1186
1187/// Handles intrinsic functions for postvisit ApplicationExpr.
1188ast::Expr const * CallAdapter::handleIntrinsics(
1189                ast::ApplicationExpr const * expr ) {
1190        auto varExpr = expr->func.as<ast::VariableExpr>();
1191        if ( !varExpr || varExpr->var->linkage != ast::Linkage::Intrinsic ) {
1192                return nullptr;
1193        }
1194        std::string const & varName = varExpr->var->name;
1195
1196        // Index Intrinsic:
1197        if ( "?[?]" == varName ) {
1198                assert( expr->result );
1199                assert( 2 == expr->args.size() );
1200
1201                ast::Type const * arg1Ty = expr->args.front()->result;
1202                ast::Type const * arg2Ty = expr->args.back()->result;
1203
1204                // two cases: a[i] with first arg poly ptr, i[a] with second arg poly ptr
1205                bool isPoly1 = isPolyPtr( arg1Ty, scopeTypeVars, typeSubs ) != nullptr;
1206                bool isPoly2 = isPolyPtr( arg2Ty, scopeTypeVars, typeSubs ) != nullptr;
1207
1208                // If neither argument is a polymorphic pointer, do nothing.
1209                if ( !isPoly1 && !isPoly2 ) {
1210                        return expr;
1211                }
1212                // The arguments cannot both be polymorphic pointers.
1213                assert( !isPoly1 || !isPoly2 );
1214                // (So exactly one of the arguments is a polymorphic pointer.)
1215
1216                CodeLocation const & location = expr->location;
1217                CodeLocation const & location1 = expr->args.front()->location;
1218                CodeLocation const & location2 = expr->args.back()->location;
1219
1220                ast::UntypedExpr * ret = new ast::UntypedExpr( location,
1221                                new ast::NameExpr( location, "?+?" ) );
1222                if ( isPoly1 ) {
1223                        assert( arg1Ty );
1224                        auto arg1TyPtr = dynamic_cast<ast::PointerType const * >( arg1Ty );
1225                        assert( arg1TyPtr );
1226                        auto multiply = ast::UntypedExpr::createCall( location2, "?*?", {
1227                                expr->args.back(),
1228                                new ast::SizeofExpr( location1, deepCopy( arg1TyPtr->base ) ),
1229                        } );
1230                        ret->args.push_back( expr->args.front() );
1231                        ret->args.push_back( multiply );
1232                } else {
1233                        assert( isPoly2 );
1234                        assert( arg2Ty );
1235                        auto arg2TyPtr = dynamic_cast<ast::PointerType const * >( arg2Ty );
1236                        assert( arg2TyPtr );
1237                        auto multiply = ast::UntypedExpr::createCall( location1, "?*?", {
1238                                expr->args.front(),
1239                                new ast::SizeofExpr( location2, deepCopy( arg2TyPtr->base ) ),
1240                        } );
1241                        ret->args.push_back( multiply );
1242                        ret->args.push_back( expr->args.back() );
1243                }
1244                ret->result = ast::deepCopy( expr->result );
1245                ret->env = expr->env ? expr->env : ret->env;
1246                return ret;
1247        // Dereference Intrinsic:
1248        } else if ( "*?" == varName ) {
1249                assert( expr->result );
1250                assert( 1 == expr->args.size() );
1251
1252                auto ptrExpr = expr->args.front();
1253                auto ptrTy = ptrExpr->result.as<ast::PointerType>();
1254                assert(ptrTy); // thing being deref'd must be pointer
1255                auto referentTy = ptrTy->base;
1256                assert(referentTy);
1257
1258                // If this isn't for a poly type, then do nothing.
1259                if ( !isPolyType( referentTy, scopeTypeVars, typeSubs ) ) {
1260                        return expr;
1261                }
1262
1263                // Remove dereference from polymorphic types since they are boxed.
1264                ast::Expr * ret = ast::deepCopy( expr->args.front() );
1265                // Fix expression type to remove pointer.
1266                ret->result = expr->result;
1267                // apply pointer decay
1268                if (auto retArTy = ret->result.as<ast::ArrayType>()) {
1269                        ret->result = new ast::PointerType( retArTy->base );
1270                }
1271                ret->env = expr->env ? expr->env : ret->env;
1272                return ret;
1273        // Post-Increment/Decrement Intrinsics:
1274        } else if ( "?++" == varName || "?--" == varName ) {
1275                assert( expr->result );
1276                assert( 1 == expr->args.size() );
1277
1278                ast::Type const * baseType =
1279                        isPolyType( expr->result, scopeTypeVars, typeSubs );
1280                if ( nullptr == baseType ) {
1281                        return expr;
1282                }
1283                ast::Type * tempType = ast::deepCopy( expr->result );
1284                if ( typeSubs ) {
1285                        auto result = typeSubs->apply( tempType );
1286                        tempType = ast::mutate( result.node.release() );
1287                }
1288                CodeLocation const & location = expr->location;
1289                ast::ObjectDecl * newObj = makeTemporary( location, tempType );
1290                ast::VariableExpr * tempExpr =
1291                        new ast::VariableExpr( location, newObj );
1292                ast::UntypedExpr * assignExpr = new ast::UntypedExpr( location,
1293                        new ast::NameExpr( location, "?=?" ) );
1294                assignExpr->args.push_back( ast::deepCopy( tempExpr ) );
1295                if ( auto address = expr->args.front().as<ast::AddressExpr>() ) {
1296                        assignExpr->args.push_back( ast::deepCopy( address->arg ) );
1297                } else {
1298                        assignExpr->args.push_back( ast::deepCopy( expr->args.front() ) );
1299                }
1300                return new ast::CommaExpr( location,
1301                        new ast::CommaExpr( location,
1302                                assignExpr,
1303                                makeIncrDecrExpr( location, expr, baseType, "?++" == varName )
1304                        ),
1305                        tempExpr
1306                );
1307        // Pre-Increment/Decrement Intrinsics:
1308        } else if ( "++?" == varName || "--?" == varName ) {
1309                assert( expr->result );
1310                assert( 1 == expr->args.size() );
1311
1312                ast::Type const * baseType =
1313                        isPolyType( expr->result, scopeTypeVars, typeSubs );
1314                if ( nullptr == baseType ) {
1315                        return expr;
1316                }
1317                return makeIncrDecrExpr(
1318                        expr->location, expr, baseType, "++?" == varName );
1319        // Addition and Subtraction Intrinsics:
1320        } else if ( "?+?" == varName || "?-?" == varName ) {
1321                assert( expr->result );
1322                assert( 2 == expr->args.size() );
1323
1324                ast::Type const * arg1Ty = expr->args.front()->result;
1325                ast::Type const * arg2Ty = expr->args.back()->result;
1326
1327                bool isPoly1 = isPolyPtr( arg1Ty, scopeTypeVars, typeSubs ) != nullptr;
1328                bool isPoly2 = isPolyPtr( arg2Ty, scopeTypeVars, typeSubs ) != nullptr;
1329
1330                CodeLocation const & location = expr->location;
1331                CodeLocation const & location1 = expr->args.front()->location;
1332                CodeLocation const & location2 = expr->args.back()->location;
1333                // LHS minus RHS -> (LHS minus RHS) / sizeof(LHS)
1334                if ( isPoly1 && isPoly2 ) {
1335                        assert( "?-?" == varName );
1336                        assert( arg1Ty );
1337                        auto arg1TyPtr = dynamic_cast<ast::PointerType const * >( arg1Ty );
1338                        assert( arg1TyPtr );
1339                        auto divide = ast::UntypedExpr::createCall( location, "?/?", {
1340                                expr,
1341                                new ast::SizeofExpr( location, deepCopy( arg1TyPtr->base ) ),
1342                        } );
1343                        if ( expr->env ) divide->env = expr->env;
1344                        return divide;
1345                // LHS op RHS -> LHS op (RHS * sizeof(LHS))
1346                } else if ( isPoly1 ) {
1347                        assert( arg1Ty );
1348                        auto arg1TyPtr = dynamic_cast<ast::PointerType const * >( arg1Ty );
1349                        assert( arg1TyPtr );
1350                        auto multiply = ast::UntypedExpr::createCall( location2, "?*?", {
1351                                expr->args.back(),
1352                                new ast::SizeofExpr( location1, deepCopy( arg1TyPtr->base ) ),
1353                        } );
1354                        return ast::mutate_field_index(
1355                                expr, &ast::ApplicationExpr::args, 1, multiply );
1356                // LHS op RHS -> (LHS * sizeof(RHS)) op RHS
1357                } else if ( isPoly2 ) {
1358                        assert( arg2Ty );
1359                        auto arg2TyPtr = dynamic_cast<ast::PointerType const * >( arg2Ty );
1360                        assert( arg2TyPtr );
1361                        auto multiply = ast::UntypedExpr::createCall( location1, "?*?", {
1362                                expr->args.front(),
1363                                new ast::SizeofExpr( location2, deepCopy( arg2TyPtr->base ) ),
1364                        } );
1365                        return ast::mutate_field_index(
1366                                expr, &ast::ApplicationExpr::args, 0, multiply );
1367                }
1368        // Addition and Subtration Relative Assignment Intrinsics:
1369        } else if ( "?+=?" == varName || "?-=?" == varName ) {
1370                assert( expr->result );
1371                assert( 2 == expr->args.size() );
1372
1373                CodeLocation const & location1 = expr->args.front()->location;
1374                CodeLocation const & location2 = expr->args.back()->location;
1375                auto baseType = isPolyPtr( expr->result, scopeTypeVars, typeSubs );
1376                // LHS op RHS -> LHS op (RHS * sizeof(LHS))
1377                if ( baseType ) {
1378                        auto multiply = ast::UntypedExpr::createCall( location2, "?*?", {
1379                                expr->args.back(),
1380                                new ast::SizeofExpr( location1, deepCopy( baseType ) ),
1381                        } );
1382                        return ast::mutate_field_index(
1383                                expr, &ast::ApplicationExpr::args, 1, multiply );
1384                }
1385        }
1386        return expr;
1387}
1388
1389ast::ObjectDecl * CallAdapter::makeTemporary(
1390                CodeLocation const & location, ast::Type const * type ) {
1391        auto newObj = new ast::ObjectDecl( location, tmpNamer.newName(), type );
1392        stmtsToAddBefore.push_back( new ast::DeclStmt( location, newObj ) );
1393        return newObj;
1394}
1395
1396// --------------------------------------------------------------------------
1397/// Modifies declarations to accept implicit parameters.
1398/// * Move polymorphic returns in function types to pointer-type parameters.
1399/// * Adds type size and assertion parameters to parameter lists.
1400struct DeclAdapter final {
1401        ast::FunctionDecl const * previsit( ast::FunctionDecl const * decl );
1402        ast::FunctionDecl const * postvisit( ast::FunctionDecl const * decl );
1403private:
1404        void addAdapters( ast::FunctionDecl * decl, TypeVarMap & localTypeVars );
1405};
1406
1407ast::ObjectDecl * makeObj(
1408                CodeLocation const & location, std::string const & name ) {
1409        // The size/align parameters may be unused, so add the unused attribute.
1410        return new ast::ObjectDecl( location, name,
1411                makeLayoutCType(),
1412                nullptr, ast::Storage::Classes(), ast::Linkage::C, nullptr,
1413                { new ast::Attribute( "unused" ) } );
1414}
1415
1416/// A modified and specialized version of ast::add_qualifiers.
1417ast::Type const * addConst( ast::Type const * type ) {
1418        ast::CV::Qualifiers cvq = { ast::CV::Const };
1419        if ( ( type->qualifiers & cvq ) != 0 ) return type;
1420        auto mutType = ast::mutate( type );
1421        mutType->qualifiers |= cvq;
1422        return mutType;
1423}
1424
1425ast::FunctionDecl const * DeclAdapter::previsit( ast::FunctionDecl const * decl ) {
1426        TypeVarMap localTypeVars;
1427        makeTypeVarMap( decl, localTypeVars );
1428
1429        auto mutDecl = mutate( decl );
1430
1431        // Move polymorphic return type to parameter list.
1432        if ( isDynRet( mutDecl->type ) ) {
1433                auto ret = strict_dynamic_cast<ast::ObjectDecl *>(
1434                        mutDecl->returns.front().get_and_mutate() );
1435                ret->set_type( new ast::PointerType( ret->type ) );
1436                mutDecl->params.insert( mutDecl->params.begin(), ret );
1437                mutDecl->returns.erase( mutDecl->returns.begin() );
1438                ret->init = nullptr;
1439        }
1440
1441        // Add size/align and assertions for type parameters to parameter list.
1442        ast::vector<ast::DeclWithType> inferredParams;
1443        ast::vector<ast::DeclWithType> layoutParams;
1444        for ( ast::ptr<ast::TypeDecl> & typeParam : mutDecl->type_params ) {
1445                auto mutParam = mutate( typeParam.get() );
1446                // Add all size and alignment parameters to parameter list.
1447                if ( mutParam->isComplete() ) {
1448                        ast::TypeInstType paramType( mutParam );
1449                        std::string paramName = Mangle::mangleType( &paramType );
1450
1451                        auto sizeParam = makeObj( typeParam->location, sizeofName( paramName ) );
1452                        layoutParams.emplace_back( sizeParam );
1453
1454                        auto alignParam = makeObj( typeParam->location, alignofName( paramName ) );
1455                        layoutParams.emplace_back( alignParam );
1456                }
1457                // Assertions should be stored in the main list.
1458                assert( mutParam->assertions.empty() );
1459                typeParam = mutParam;
1460        }
1461        for ( ast::ptr<ast::DeclWithType> & assert : mutDecl->assertions ) {
1462                ast::DeclWithType * mutAssert = ast::mutate( assert.get() );
1463                // Assertion parameters may not be used in body,
1464                // pass along with unused attribute.
1465                mutAssert->attributes.push_back( new ast::Attribute( "unused" ) );
1466                mutAssert->set_type( addConst( mutAssert->get_type() ) );
1467                inferredParams.emplace_back( mutAssert );
1468        }
1469        mutDecl->assertions.clear();
1470
1471        // Prepend each argument group. From last group to first. addAdapters
1472        // does do the same, it just does it itself and see all other parameters.
1473        spliceBegin( mutDecl->params, inferredParams );
1474        spliceBegin( mutDecl->params, layoutParams );
1475        addAdapters( mutDecl, localTypeVars );
1476
1477        // Now have to update the type to match the declaration.
1478        ast::FunctionType * type = new ast::FunctionType(
1479                mutDecl->type->isVarArgs, mutDecl->type->qualifiers );
1480        // The forall clauses don't match until Eraser. The assertions are empty.
1481        for ( auto param : mutDecl->params ) {
1482                type->params.emplace_back( param->get_type() );
1483        }
1484        for ( auto retval : mutDecl->returns ) {
1485                type->returns.emplace_back( retval->get_type() );
1486        }
1487        mutDecl->type = type;
1488
1489        return mutDecl;
1490}
1491
1492ast::FunctionDecl const * DeclAdapter::postvisit(
1493                ast::FunctionDecl const * decl ) {
1494        ast::FunctionDecl * mutDecl = mutate( decl );
1495        if ( !mutDecl->returns.empty() && mutDecl->stmts
1496                        // Intrinsic functions won't be using the _retval so no need to
1497                        // generate it.
1498                        && mutDecl->linkage != ast::Linkage::Intrinsic
1499                        // Remove check for prefix once thunks properly use ctor/dtors.
1500                        && !isPrefix( mutDecl->name, "_thunk" )
1501                        && !isPrefix( mutDecl->name, "_adapter" ) ) {
1502                assert( 1 == mutDecl->returns.size() );
1503                ast::DeclWithType const * retval = mutDecl->returns.front();
1504                if ( "" == retval->name ) {
1505                        retval = ast::mutate_field(
1506                                retval, &ast::DeclWithType::name, "_retval" );
1507                        mutDecl->returns.front() = retval;
1508                }
1509                auto stmts = mutDecl->stmts.get_and_mutate();
1510                stmts->kids.push_front( new ast::DeclStmt( retval->location, retval ) );
1511                ast::DeclWithType * newRet = ast::deepCopy( retval );
1512                mutDecl->returns.front() = newRet;
1513        }
1514        // Errors should have been caught by this point, remove initializers from
1515        // parameters to allow correct codegen of default arguments.
1516        for ( ast::ptr<ast::DeclWithType> & param : mutDecl->params ) {
1517                if ( auto obj = param.as<ast::ObjectDecl>() ) {
1518                        param = ast::mutate_field( obj, &ast::ObjectDecl::init, nullptr );
1519                }
1520        }
1521        return mutDecl;
1522}
1523
1524void DeclAdapter::addAdapters(
1525                ast::FunctionDecl * mutDecl, TypeVarMap & localTypeVars ) {
1526        ast::vector<ast::FunctionType> functions;
1527        for ( ast::ptr<ast::DeclWithType> & arg : mutDecl->params ) {
1528                ast::Type const * type = arg->get_type();
1529                type = findAndReplaceFunction( type, functions, localTypeVars, needsAdapter );
1530                arg.get_and_mutate()->set_type( type );
1531        }
1532        std::set<std::string> adaptersDone;
1533        for ( ast::ptr<ast::FunctionType> const & func : functions ) {
1534                std::string mangleName = mangleAdapterName( func, localTypeVars );
1535                if ( adaptersDone.find( mangleName ) != adaptersDone.end() ) {
1536                        continue;
1537                }
1538                std::string adapterName = makeAdapterName( mangleName );
1539                // The adapter may not actually be used, so make sure it has unused.
1540                mutDecl->params.insert( mutDecl->params.begin(), new ast::ObjectDecl(
1541                        mutDecl->location, adapterName,
1542                        new ast::PointerType( makeAdapterType( func, localTypeVars ) ),
1543                        nullptr, {}, {}, nullptr,
1544                        { new ast::Attribute( "unused" ) } ) );
1545                adaptersDone.insert( adaptersDone.begin(), mangleName );
1546        }
1547}
1548
1549// --------------------------------------------------------------------------
1550/// Corrects the floating nodes created in CallAdapter.
1551struct RewireAdapters final : public ast::WithGuards {
1552        ScopedMap<std::string, ast::ObjectDecl const *> adapters;
1553        void beginScope() { adapters.beginScope(); }
1554        void endScope() { adapters.endScope(); }
1555        void previsit( ast::FunctionDecl const * decl );
1556        ast::VariableExpr const * previsit( ast::VariableExpr const * expr );
1557};
1558
1559void RewireAdapters::previsit( ast::FunctionDecl const * decl ) {
1560        GuardScope( adapters );
1561        for ( ast::ptr<ast::DeclWithType> const & param : decl->params ) {
1562                if ( auto objectParam = param.as<ast::ObjectDecl>() ) {
1563                        adapters.insert( objectParam->name, objectParam );
1564                }
1565        }
1566}
1567
1568ast::VariableExpr const * RewireAdapters::previsit(
1569                ast::VariableExpr const * expr ) {
1570        // If the node is not floating, we can skip.
1571        if ( expr->var->isManaged() ) return expr;
1572        auto it = adapters.find( expr->var->name );
1573        assertf( it != adapters.end(), "Could not correct floating node." );
1574        return ast::mutate_field( expr, &ast::VariableExpr::var, it->second );
1575}
1576
1577// --------------------------------------------------------------------------
1578/// Inserts code to access polymorphic layout inforation.
1579/// * Replaces member and size/alignment/offsetof expressions on polymorphic
1580///   generic types with calculated expressions.
1581/// * Replaces member expressions for polymorphic types with calculated
1582///   add-field-offset-and-dereference.
1583/// * Calculates polymorphic offsetof expressions from offset array.
1584/// * Inserts dynamic calculation of polymorphic type layouts where needed.
1585struct PolyGenericCalculator final :
1586                public ast::WithConstTypeSubstitution,
1587                public ast::WithDeclsToAdd<>,
1588                public ast::WithGuards,
1589                public ast::WithStmtsToAdd<>,
1590                public ast::WithVisitorRef<PolyGenericCalculator> {
1591        PolyGenericCalculator();
1592
1593        void previsit( ast::FunctionDecl const * decl );
1594        void previsit( ast::TypedefDecl const * decl );
1595        void previsit( ast::TypeDecl const * decl );
1596        ast::Decl const * postvisit( ast::TypeDecl const * decl );
1597        ast::StructDecl const * previsit( ast::StructDecl const * decl );
1598        ast::UnionDecl const * previsit( ast::UnionDecl const * decl );
1599        ast::DeclStmt const * previsit( ast::DeclStmt const * stmt );
1600        ast::Expr const * postvisit( ast::MemberExpr const * expr );
1601        void previsit( ast::AddressExpr const * expr );
1602        ast::Expr const * postvisit( ast::AddressExpr const * expr );
1603        ast::Expr const * postvisit( ast::SizeofExpr const * expr );
1604        ast::Expr const * postvisit( ast::AlignofExpr const * expr );
1605        ast::Expr const * postvisit( ast::OffsetofExpr const * expr );
1606        ast::Expr const * postvisit( ast::OffsetPackExpr const * expr );
1607
1608        void beginScope();
1609        void endScope();
1610private:
1611        /// Makes a new variable in the current scope with the given name,
1612        /// type and optional initializer.
1613        ast::ObjectDecl * makeVar(
1614                        CodeLocation const & location, std::string const & name,
1615                        ast::Type const * type, ast::Init const * init = nullptr );
1616        /// Returns true if the type has a dynamic layout;
1617        /// such a layout will be stored in appropriately-named local variables
1618        /// when the function returns.
1619        bool findGeneric( CodeLocation const & location, ast::Type const * );
1620        /// Adds type parameters to the layout call; will generate the
1621        /// appropriate parameters if needed.
1622        void addSTypeParamsToLayoutCall(
1623                ast::UntypedExpr * layoutCall,
1624                const ast::vector<ast::Type> & otypeParams );
1625        /// Change the type of generic aggregate members to char[].
1626        void mutateMembers( ast::AggregateDecl * aggr );
1627        /// Returns the calculated sizeof/alignof expressions for type, or
1628        /// nullptr for use C size/alignof().
1629        ast::Expr const * genSizeof( CodeLocation const &, ast::Type const * );
1630        ast::Expr const * genAlignof( CodeLocation const &, ast::Type const * );
1631        /// Enters a new scope for type-variables,
1632        /// adding the type variables from the provided type.
1633        void beginTypeScope( ast::Type const * );
1634
1635        /// The type variables and polymorphic parameters currently in scope.
1636        TypeVarMap scopeTypeVars;
1637        /// Set of generic type layouts known in the current scope,
1638        /// indexed by sizeofName.
1639        ScopedSet<std::string> knownLayouts;
1640        /// Set of non-generic types for which the offset array exists in the
1641        /// current scope, indexed by offsetofName.
1642        ScopedSet<std::string> knownOffsets;
1643        /// Namer for VLA (variable length array) buffers.
1644        UniqueName bufNamer;
1645        /// If the argument of an AddressExpr is MemberExpr, it is stored here.
1646        ast::MemberExpr const * addrMember = nullptr;
1647};
1648
1649PolyGenericCalculator::PolyGenericCalculator() :
1650        knownLayouts(), knownOffsets(), bufNamer( "_buf" )
1651{}
1652
1653static ast::Type * polyToMonoTypeRec( CodeLocation const & loc,
1654                ast::Type const * ty ) {
1655        ast::Type * ret;
1656        if ( auto aTy = dynamic_cast<ast::ArrayType const *>( ty ) ) {
1657                // recursive case
1658                auto monoBase = polyToMonoTypeRec( loc, aTy->base );
1659                ret = new ast::ArrayType( monoBase, aTy->dimension,
1660                        aTy->isVarLen, aTy->isStatic, aTy->qualifiers );
1661        } else {
1662                // base case
1663                auto charType = new ast::BasicType( ast::BasicKind::Char );
1664                auto size = new ast::NameExpr( loc,
1665                        sizeofName( Mangle::mangleType( ty ) ) );
1666                ret = new ast::ArrayType( charType, size,
1667                        ast::VariableLen, ast::DynamicDim, ast::CV::Qualifiers() );
1668        }
1669        return ret;
1670}
1671
1672/// Converts polymorphic type into a suitable monomorphic representation.
1673/// Simple cases: T -> __attribute__(( aligned(8) )) char[sizeof_T];
1674/// Array cases: T[eOut][eIn] ->  __attribute__(( aligned(8) )) char[eOut][eIn][sizeof_T];
1675ast::Type * polyToMonoType( CodeLocation const & loc, ast::Type const * ty ) {
1676        auto ret = polyToMonoTypeRec( loc, ty );
1677        ret->attributes.emplace_back( new ast::Attribute( "aligned",
1678                { ast::ConstantExpr::from_int( loc, 8 ) } ) );
1679        return ret;
1680}
1681
1682void PolyGenericCalculator::previsit( ast::FunctionDecl const * decl ) {
1683        GuardScope( *this );
1684        beginTypeScope( decl->type );
1685}
1686
1687void PolyGenericCalculator::previsit( ast::TypedefDecl const * decl ) {
1688        assertf( false, "All typedef declarations should be removed." );
1689        beginTypeScope( decl->base );
1690}
1691
1692void PolyGenericCalculator::previsit( ast::TypeDecl const * decl ) {
1693        addToTypeVarMap( decl, scopeTypeVars );
1694}
1695
1696ast::Decl const * PolyGenericCalculator::postvisit(
1697                ast::TypeDecl const * decl ) {
1698        ast::Type const * base = decl->base;
1699        if ( nullptr == base ) return decl;
1700
1701        // Add size/align variables for opaque type declarations.
1702        ast::TypeInstType inst( decl->name, decl );
1703        std::string typeName = Mangle::mangleType( &inst );
1704
1705        ast::ObjectDecl * sizeDecl = new ast::ObjectDecl( decl->location,
1706                sizeofName( typeName ), makeLayoutCType(),
1707                new ast::SingleInit( decl->location,
1708                        new ast::SizeofExpr( decl->location, deepCopy( base ) )
1709                )
1710        );
1711        ast::ObjectDecl * alignDecl = new ast::ObjectDecl( decl->location,
1712                alignofName( typeName ), makeLayoutCType(),
1713                new ast::SingleInit( decl->location,
1714                        new ast::AlignofExpr( decl->location, deepCopy( base ) )
1715                )
1716        );
1717
1718        // Ensure that the initializing sizeof/alignof exprs are properly mutated.
1719        sizeDecl->accept( *visitor );
1720        alignDecl->accept( *visitor );
1721
1722        // A little trick to replace this with two declarations.
1723        // Adding after makes sure that there is no conflict with adding stmts.
1724        declsToAddAfter.push_back( alignDecl );
1725        return sizeDecl;
1726}
1727
1728ast::StructDecl const * PolyGenericCalculator::previsit(
1729                ast::StructDecl const * decl ) {
1730        auto mutDecl = mutate( decl );
1731        mutateMembers( mutDecl );
1732        return mutDecl;
1733}
1734
1735ast::UnionDecl const * PolyGenericCalculator::previsit(
1736                ast::UnionDecl const * decl ) {
1737        auto mutDecl = mutate( decl );
1738        mutateMembers( mutDecl );
1739        return mutDecl;
1740}
1741
1742ast::DeclStmt const * PolyGenericCalculator::previsit( ast::DeclStmt const * stmt ) {
1743        ast::ObjectDecl const * decl = stmt->decl.as<ast::ObjectDecl>();
1744        if ( !decl || !findGeneric( decl->location, decl->type ) ) {
1745                return stmt;
1746        }
1747
1748        // Change initialization of a polymorphic value object to allocate via a
1749        // variable-length-array (alloca cannot be safely used in loops).
1750        ast::ObjectDecl * newBuf = new ast::ObjectDecl( decl->location,
1751                bufNamer.newName(),
1752                polyToMonoType( decl->location, decl->type ),
1753                nullptr, {}, ast::Linkage::C
1754        );
1755        stmtsToAddBefore.push_back( new ast::DeclStmt( stmt->location, newBuf ) );
1756
1757        // If the object has a cleanup attribute, the clean-up should be on the
1758        // buffer, not the pointer. [Perhaps this should be lifted?]
1759        auto matchAndMove = [newBuf]( ast::ptr<ast::Attribute> & attr ) {
1760                if ( "cleanup" == attr->name ) {
1761                        newBuf->attributes.push_back( attr );
1762                        return true;
1763                }
1764                return false;
1765        };
1766
1767        auto mutDecl = mutate( decl );
1768
1769        // Forally, side effects are not safe in this function. But it works.
1770        erase_if( mutDecl->attributes, matchAndMove );
1771
1772        // Change the decl's type.
1773        // Upon finishing the box pass, it shall be void*.
1774        // At this middle-of-box-pass point, that type is T.
1775
1776        // example 1
1777        // before box:                                  T     t ;
1778        // before here:  char _bufxx    [_sizeof_Y1T];  T     t = _bufxx;
1779        // after here:   char _bufxx    [_sizeof_Y1T];  T     t = _bufxx;  (no change here - non array case)
1780        // after box:    char _bufxx    [_sizeof_Y1T];  void *t = _bufxx;
1781
1782        // example 2
1783        // before box:                                  T     t[42] ;
1784        // before here:  char _bufxx[42][_sizeof_Y1T];  T     t[42] = _bufxx;
1785        // after here:   char _bufxx[42][_sizeof_Y1T];  T     t     = _bufxx;
1786        // after box:    char _bufxx[42][_sizeof_Y1T];  void *t     = _bufxx;
1787
1788        // Strip all "array of" wrappers
1789        while ( auto arrayType = dynamic_cast<ast::ArrayType const *>( mutDecl->type.get() ) ) {
1790                mutDecl->type = arrayType->base;
1791        }
1792
1793        mutDecl->init = new ast::SingleInit( decl->location,
1794                new ast::VariableExpr( decl->location, newBuf ) );
1795
1796        return ast::mutate_field( stmt, &ast::DeclStmt::decl, mutDecl );
1797}
1798
1799/// Checks if memberDecl matches the decl from an aggregate.
1800bool isMember( ast::DeclWithType const * memberDecl, ast::Decl const * decl ) {
1801        // No matter the field, if the name is different it is not the same.
1802        if ( memberDecl->name != decl->name ) {
1803                return false;
1804        }
1805
1806        if ( memberDecl->name.empty() ) {
1807                // Plan-9 Field: Match on unique_id.
1808                return ( memberDecl->uniqueId == decl->uniqueId );
1809        }
1810
1811        ast::DeclWithType const * declWithType =
1812                strict_dynamic_cast<ast::DeclWithType const *>( decl );
1813
1814        if ( memberDecl->mangleName.empty() || declWithType->mangleName.empty() ) {
1815                // Tuple-Element Field: Expect neither had mangled name;
1816                // accept match on simple name (like field_2) only.
1817                assert( memberDecl->mangleName.empty() );
1818                assert( declWithType->mangleName.empty() );
1819                return true;
1820        }
1821
1822        // Ordinary Field: Use full name to accommodate overloading.
1823        return ( memberDecl->mangleName == declWithType->mangleName );
1824}
1825
1826/// Finds the member in the base list that matches the given declaration;
1827/// returns its index, or -1 if not present.
1828long findMember( ast::DeclWithType const * memberDecl,
1829                const ast::vector<ast::Decl> & baseDecls ) {
1830        for ( auto const & [index, value] : enumerate( baseDecls ) ) {
1831                if ( isMember( memberDecl, value.get() ) ) {
1832                        return index;
1833                }
1834        }
1835        return -1;
1836}
1837
1838/// Returns an index expression into the offset array for a type.
1839ast::Expr * makeOffsetIndex( CodeLocation const & location,
1840                ast::Type const * objectType, long i ) {
1841        std::string name = offsetofName( Mangle::mangleType( objectType ) );
1842        return ast::UntypedExpr::createCall( location, "?[?]", {
1843                new ast::NameExpr( location, name ),
1844                ast::ConstantExpr::from_ulong( location, i ),
1845        } );
1846}
1847
1848ast::Expr const * PolyGenericCalculator::postvisit(
1849                ast::MemberExpr const * expr ) {
1850        // Only mutate member expressions for polymorphic types.
1851        ast::Type const * objectType = hasPolyBase(
1852                expr->aggregate->result, scopeTypeVars
1853        );
1854        if ( !objectType ) return expr;
1855        // Ensure layout for this type is available.
1856        // The boolean result is ignored.
1857        findGeneric( expr->location, objectType );
1858
1859        // Replace member expression with dynamically-computed layout expression.
1860        ast::Expr * newMemberExpr = nullptr;
1861        if ( auto structType = dynamic_cast<ast::StructInstType const *>( objectType ) ) {
1862                long offsetIndex = findMember( expr->member, structType->base->members );
1863                if ( -1 == offsetIndex ) return expr;
1864
1865                // Replace member expression with pointer to struct plus offset.
1866                ast::UntypedExpr * fieldLoc = new ast::UntypedExpr( expr->location,
1867                                new ast::NameExpr( expr->location, "?+?" ) );
1868                ast::Expr * aggr = deepCopy( expr->aggregate );
1869                aggr->env = nullptr;
1870                fieldLoc->args.push_back( aggr );
1871                fieldLoc->args.push_back(
1872                        makeOffsetIndex( expr->location, objectType, offsetIndex ) );
1873                fieldLoc->result = deepCopy( expr->result );
1874                newMemberExpr = fieldLoc;
1875        // Union members are all at offset zero, so just use the aggregate expr.
1876        } else if ( dynamic_cast<ast::UnionInstType const *>( objectType ) ) {
1877                ast::Expr * aggr = deepCopy( expr->aggregate );
1878                aggr->env = nullptr;
1879                aggr->result = deepCopy( expr->result );
1880                newMemberExpr = aggr;
1881        } else {
1882                return expr;
1883        }
1884        assert( newMemberExpr );
1885
1886        // Must apply the generic substitution to the member type to handle cases
1887        // where the member is a generic parameter subsituted by a known concrete
1888        // type. [ex]
1889        //      forall( T ) struct Box { T x; }
1890        //      forall( T ) void f() {
1891        //              Box( T * ) b; b.x;
1892        //      }
1893        // TODO: expr->result should be exactly expr->member->get_type() after
1894        // substitution, so it doesn't seem like it should be necessary to apply
1895        // the substitution manually. For some reason this is not currently the
1896        // case. This requires more investigation.
1897        ast::ptr<ast::Type> memberType = deepCopy( expr->member->get_type() );
1898        ast::TypeSubstitution sub = genericSubstitution( objectType );
1899        sub.apply( memberType );
1900
1901        // Not all members of a polymorphic type are themselves of a polymorphic
1902        // type; in this case the member expression should be wrapped and
1903        // dereferenced to form an lvalue.
1904        if ( !isPolyType( memberType, scopeTypeVars ) ) {
1905                auto ptrCastExpr = new ast::CastExpr( expr->location, newMemberExpr,
1906                        new ast::PointerType( memberType ) );
1907                auto derefExpr = ast::UntypedExpr::createDeref( expr->location,
1908                        ptrCastExpr );
1909                newMemberExpr = derefExpr;
1910        }
1911
1912        return newMemberExpr;
1913}
1914
1915void PolyGenericCalculator::previsit( ast::AddressExpr const * expr ) {
1916        GuardValue( addrMember ) = expr->arg.as<ast::MemberExpr>();
1917}
1918
1919ast::Expr const * PolyGenericCalculator::postvisit(
1920                ast::AddressExpr const * expr ) {
1921        // arg has to have been a MemberExpr and has been mutated.
1922        if ( nullptr == addrMember || expr->arg == addrMember ) {
1923                return expr;
1924        }
1925        ast::UntypedExpr const * untyped = expr->arg.as<ast::UntypedExpr>();
1926        if ( !untyped || getFunctionName( untyped ) != "?+?" ) {
1927                return expr;
1928        }
1929        // MemberExpr was converted to pointer + offset; and it is not valid C to
1930        // take the address of an addition, so strip away the address-of.
1931        // It also preserves the env value.
1932        return ast::mutate_field( expr->arg.get(), &ast::Expr::env, expr->env );
1933}
1934
1935ast::Expr const * PolyGenericCalculator::postvisit(
1936                ast::SizeofExpr const * expr ) {
1937        ast::Type const * type = expr->type ? expr->type : expr->expr->result;
1938        ast::Expr const * gen = genSizeof( expr->location, type );
1939        return ( gen ) ? gen : expr;
1940}
1941
1942ast::Expr const * PolyGenericCalculator::postvisit(
1943                ast::AlignofExpr const * expr ) {
1944        ast::Type const * type = expr->type ? expr->type : expr->expr->result;
1945        ast::Expr const * gen = genAlignof( expr->location, type );
1946        return ( gen ) ? gen : expr;
1947}
1948
1949ast::Expr const * PolyGenericCalculator::postvisit(
1950                ast::OffsetofExpr const * expr ) {
1951        ast::Type const * type = expr->type;
1952        if ( !findGeneric( expr->location, type ) ) return expr;
1953
1954        // Structures replace offsetof expression with an index into offset array.
1955        if ( auto structType = dynamic_cast<ast::StructInstType const *>( type ) ) {
1956                long offsetIndex = findMember( expr->member, structType->base->members );
1957                if ( -1 == offsetIndex ) return expr;
1958
1959                return makeOffsetIndex( expr->location, type, offsetIndex );
1960        // All union members are at offset zero.
1961        } else if ( dynamic_cast<ast::UnionInstType const *>( type ) ) {
1962                return ast::ConstantExpr::from_ulong( expr->location, 0 );
1963        } else {
1964                return expr;
1965        }
1966}
1967
1968ast::Expr const * PolyGenericCalculator::postvisit(
1969                ast::OffsetPackExpr const * expr ) {
1970        ast::StructInstType const * type = expr->type;
1971
1972        // Pull offset back from generated type information.
1973        if ( findGeneric( expr->location, type ) ) {
1974                return new ast::NameExpr( expr->location,
1975                        offsetofName( Mangle::mangleType( type ) ) );
1976        }
1977
1978        std::string offsetName = offsetofName( Mangle::mangleType( type ) );
1979        // Use the already generated offsets for this type.
1980        if ( knownOffsets.contains( offsetName ) ) {
1981                return new ast::NameExpr( expr->location, offsetName );
1982        }
1983
1984        knownOffsets.insert( offsetName );
1985
1986        // Build initializer list for offset array.
1987        ast::vector<ast::Init> inits;
1988        for ( ast::ptr<ast::Decl> const & member : type->base->members ) {
1989                auto memberDecl = member.as<ast::DeclWithType>();
1990                assertf( memberDecl, "Requesting offset of non-DWT member: %s",
1991                        toCString( member ) );
1992                inits.push_back( new ast::SingleInit( expr->location,
1993                        new ast::OffsetofExpr( expr->location,
1994                                deepCopy( type ),
1995                                memberDecl
1996                        )
1997                ) );
1998        }
1999
2000        auto offsetArray = makeVar( expr->location, offsetName,
2001                new ast::ArrayType(
2002                        makeLayoutType(),
2003                        ast::ConstantExpr::from_ulong( expr->location, inits.size() ),
2004                        ast::FixedLen,
2005                        ast::DynamicDim
2006                ),
2007                new ast::ListInit( expr->location, std::move( inits ) )
2008        );
2009
2010        return new ast::VariableExpr( expr->location, offsetArray );
2011}
2012
2013void PolyGenericCalculator::beginScope() {
2014        knownLayouts.beginScope();
2015        knownOffsets.beginScope();
2016}
2017
2018void PolyGenericCalculator::endScope() {
2019        knownOffsets.endScope();
2020        knownLayouts.endScope();
2021}
2022
2023ast::ObjectDecl * PolyGenericCalculator::makeVar(
2024                CodeLocation const & location, std::string const & name,
2025                ast::Type const * type, ast::Init const * init ) {
2026        ast::ObjectDecl * ret = new ast::ObjectDecl( location, name, type, init );
2027        stmtsToAddBefore.push_back( new ast::DeclStmt( location, ret ) );
2028        return ret;
2029}
2030
2031/// Returns true if any of the otype parameters have a dynamic layout; and
2032/// puts all otype parameters in the output list.
2033bool findGenericParams(
2034                ast::vector<ast::Type> & out,
2035                ast::vector<ast::TypeDecl> const & baseParams,
2036                ast::vector<ast::Expr> const & typeParams ) {
2037        bool hasDynamicLayout = false;
2038
2039        for ( auto const & [baseParam, typeParam] : group_iterate(
2040                        baseParams, typeParams ) ) {
2041                if ( !baseParam->isComplete() ) continue;
2042                ast::TypeExpr const * typeExpr = typeParam.as<ast::TypeExpr>();
2043                assertf( typeExpr, "All type parameters should be type expressions." );
2044
2045                ast::Type const * type = typeExpr->type.get();
2046                out.push_back( type );
2047                if ( isPolyType( type ) ) hasDynamicLayout = true;
2048        }
2049
2050        return hasDynamicLayout;
2051}
2052
2053bool PolyGenericCalculator::findGeneric(
2054                CodeLocation const & location, ast::Type const * type ) {
2055        type = replaceTypeInst( type, typeSubs );
2056
2057        if ( auto inst = dynamic_cast<ast::TypeInstType const *>( type ) ) {
2058                // Assumes that getting put in the scopeTypeVars includes having the
2059                // layout variables set.
2060                if ( scopeTypeVars.contains( *inst ) ) {
2061                        return true;
2062                }
2063        } else if ( auto inst = dynamic_cast<ast::StructInstType const *>( type ) ) {
2064                // Check if this type already has a layout generated for it.
2065                std::string typeName = Mangle::mangleType( type );
2066                if ( knownLayouts.contains( typeName ) ) return true;
2067
2068                // Check if any type parameters have dynamic layout;
2069                // If none do, this type is (or will be) monomorphized.
2070                ast::vector<ast::Type> sizedParams;
2071                if ( !findGenericParams( sizedParams,
2072                                inst->base->params, inst->params ) ) {
2073                        return false;
2074                }
2075
2076                // Insert local variables for layout and generate call to layout
2077                // function.
2078                // Done early so as not to interfere with the later addition of
2079                // parameters to the layout call.
2080                knownLayouts.insert( typeName );
2081
2082                int memberCount = inst->base->members.size();
2083                if ( 0 == memberCount ) {
2084                        // All empty structures have the same layout (size 1, align 1).
2085                        makeVar( location,
2086                                sizeofName( typeName ), makeLayoutType(),
2087                                new ast::SingleInit( location,
2088                                                ast::ConstantExpr::from_ulong( location, 1 ) ) );
2089                        makeVar( location,
2090                                alignofName( typeName ), makeLayoutType(),
2091                                new ast::SingleInit( location,
2092                                                ast::ConstantExpr::from_ulong( location, 1 ) ) );
2093                        // Since 0-length arrays are forbidden in C, skip the offset array.
2094                } else {
2095                        ast::ObjectDecl const * sizeofVar = makeVar( location,
2096                                sizeofName( typeName ), makeLayoutType(), nullptr );
2097                        ast::ObjectDecl const * alignofVar = makeVar( location,
2098                                alignofName( typeName ), makeLayoutType(), nullptr );
2099                        ast::ObjectDecl const * offsetofVar = makeVar( location,
2100                                offsetofName( typeName ),
2101                                new ast::ArrayType(
2102                                        makeLayoutType(),
2103                                        ast::ConstantExpr::from_int( location, memberCount ),
2104                                        ast::FixedLen,
2105                                        ast::DynamicDim
2106                                ),
2107                                nullptr
2108                        );
2109
2110                        // Generate call to layout function.
2111                        ast::UntypedExpr * layoutCall = new ast::UntypedExpr( location,
2112                                new ast::NameExpr( location, layoutofName( inst->base ) ),
2113                                {
2114                                        new ast::AddressExpr(
2115                                                new ast::VariableExpr( location, sizeofVar ) ),
2116                                        new ast::AddressExpr(
2117                                                new ast::VariableExpr( location, alignofVar ) ),
2118                                        new ast::VariableExpr( location, offsetofVar ),
2119                                } );
2120
2121                        addSTypeParamsToLayoutCall( layoutCall, sizedParams );
2122
2123                        stmtsToAddBefore.emplace_back(
2124                                new ast::ExprStmt( location, layoutCall ) );
2125                }
2126
2127                return true;
2128        } else if ( auto inst = dynamic_cast<ast::UnionInstType const *>( type ) ) {
2129                // Check if this type already has a layout generated for it.
2130                std::string typeName = Mangle::mangleType( type );
2131                if ( knownLayouts.contains( typeName ) ) return true;
2132
2133                // Check if any type parameters have dynamic layout;
2134                // If none do, this type is (or will be) monomorphized.
2135                ast::vector<ast::Type> sizedParams;
2136                if ( !findGenericParams( sizedParams,
2137                                inst->base->params, inst->params ) ) {
2138                        return false;
2139                }
2140
2141                // Insert local variables for layout and generate call to layout
2142                // function.
2143                // Done early so as not to interfere with the later addition of
2144                // parameters to the layout call.
2145                knownLayouts.insert( typeName );
2146
2147                ast::ObjectDecl * sizeofVar = makeVar( location,
2148                        sizeofName( typeName ), makeLayoutType() );
2149                ast::ObjectDecl * alignofVar = makeVar( location,
2150                        alignofName( typeName ), makeLayoutType() );
2151
2152                ast::UntypedExpr * layoutCall = new ast::UntypedExpr( location,
2153                        new ast::NameExpr( location, layoutofName( inst->base ) ),
2154                        {
2155                                new ast::AddressExpr(
2156                                        new ast::VariableExpr( location, sizeofVar ) ),
2157                                new ast::AddressExpr(
2158                                        new ast::VariableExpr( location, alignofVar ) ),
2159                        } );
2160
2161                addSTypeParamsToLayoutCall( layoutCall, sizedParams );
2162
2163                stmtsToAddBefore.emplace_back(
2164                        new ast::ExprStmt( location, layoutCall ) );
2165
2166                return true;
2167
2168        } else if ( auto inst = dynamic_cast<ast::ArrayType const *>( type ) ) {
2169                return findGeneric( location, inst->base );
2170        }
2171        return false;
2172}
2173
2174void PolyGenericCalculator::addSTypeParamsToLayoutCall(
2175                ast::UntypedExpr * layoutCall,
2176                const ast::vector<ast::Type> & otypeParams ) {
2177        CodeLocation const & location = layoutCall->location;
2178        ast::vector<ast::Expr> & args = layoutCall->args;
2179        for ( ast::ptr<ast::Type> const & param : otypeParams ) {
2180                if ( findGeneric( location, param ) ) {
2181                        // Push size/align vars for a generic parameter back.
2182                        std::string paramName = Mangle::mangleType( param );
2183                        args.emplace_back(
2184                                new ast::NameExpr( location, sizeofName( paramName ) ) );
2185                        args.emplace_back(
2186                                new ast::NameExpr( location, alignofName( paramName ) ) );
2187                } else {
2188                        args.emplace_back(
2189                                new ast::SizeofExpr( location, ast::deepCopy( param ) ) );
2190                        args.emplace_back(
2191                                new ast::AlignofExpr( location, ast::deepCopy( param ) ) );
2192                }
2193        }
2194}
2195
2196void PolyGenericCalculator::mutateMembers( ast::AggregateDecl * aggr ) {
2197        std::set<std::string> genericParams;
2198        for ( ast::ptr<ast::TypeDecl> const & decl : aggr->params ) {
2199                genericParams.insert( decl->name );
2200        }
2201        for ( ast::ptr<ast::Decl> & decl : aggr->members ) {
2202                auto field = decl.as<ast::ObjectDecl>();
2203                if ( nullptr == field ) continue;
2204
2205                ast::Type const * type = replaceTypeInst( field->type, typeSubs );
2206                auto typeInst = dynamic_cast<ast::TypeInstType const *>( type );
2207                if ( nullptr == typeInst ) continue;
2208
2209                // Do not try to monoporphize generic parameters.
2210                if ( scopeTypeVars.contains( ast::TypeEnvKey( *typeInst ) ) &&
2211                                !genericParams.count( typeInst->name ) ) {
2212                        // Polymorphic aggregate members should be converted into
2213                        // monomorphic members. Using char[size_T] here respects
2214                        // the expected sizing rules of an aggregate type.
2215                        decl = ast::mutate_field( field, &ast::ObjectDecl::type,
2216                                polyToMonoType( field->location, field->type ) );
2217                }
2218        }
2219}
2220
2221ast::Expr const * PolyGenericCalculator::genSizeof(
2222                CodeLocation const & location, ast::Type const * type ) {
2223        if ( auto * array = dynamic_cast<ast::ArrayType const *>( type ) ) {
2224                // Generate calculated size for possibly generic array.
2225                ast::Expr const * sizeofBase = genSizeof( location, array->base );
2226                if ( nullptr == sizeofBase ) return nullptr;
2227                ast::Expr const * dim = array->dimension;
2228                return makeOp( location, "?*?", sizeofBase, dim );
2229        } else if ( findGeneric( location, type ) ) {
2230                // Generate reference to _sizeof parameter
2231                return new ast::NameExpr( location, sizeofName(
2232                                Mangle::mangleType( type ) ) );
2233        } else {
2234                return nullptr;
2235        }
2236}
2237
2238ast::Expr const * PolyGenericCalculator::genAlignof(
2239                CodeLocation const & location, ast::Type const * type ) {
2240        if ( auto * array = dynamic_cast<ast::ArrayType const *>( type ) ) {
2241                // alignof array is alignof element
2242                return genAlignof( location, array->base );
2243        } else if ( findGeneric( location, type ) ) {
2244                // Generate reference to _alignof parameter
2245                return new ast::NameExpr( location, alignofName(
2246                                Mangle::mangleType( type ) ) );
2247        } else {
2248                return nullptr;
2249        }
2250}
2251
2252void PolyGenericCalculator::beginTypeScope( ast::Type const * type ) {
2253        GuardScope( scopeTypeVars );
2254        makeTypeVarMap( type, scopeTypeVars );
2255}
2256
2257// --------------------------------------------------------------------------
2258/// Removes unneeded or incorrect type information.
2259/// * Replaces initialization of polymorphic values with alloca.
2260/// * Replaces declaration of dtype/ftype with appropriate void expression.
2261/// * Replaces sizeof expressions of polymorphic types with a variable.
2262/// * Strips fields from generic structure declarations.
2263struct Eraser final :
2264                public ast::WithGuards {
2265        void guardTypeVarMap( ast::Type const * type ) {
2266                GuardScope( scopeTypeVars );
2267                makeTypeVarMap( type, scopeTypeVars );
2268        }
2269
2270        ast::ObjectDecl const * previsit( ast::ObjectDecl const * decl );
2271        ast::FunctionDecl const * previsit( ast::FunctionDecl const * decl );
2272        ast::FunctionDecl const * postvisit( ast::FunctionDecl const * decl );
2273        ast::TypedefDecl const * previsit( ast::TypedefDecl const * decl );
2274        ast::StructDecl const * previsit( ast::StructDecl const * decl );
2275        ast::UnionDecl const * previsit( ast::UnionDecl const * decl );
2276        void previsit( ast::TypeDecl const * decl );
2277        void previsit( ast::PointerType const * type );
2278        void previsit( ast::FunctionType const * type );
2279public:
2280        TypeVarMap scopeTypeVars;
2281};
2282
2283ast::ObjectDecl const * Eraser::previsit( ast::ObjectDecl const * decl ) {
2284        guardTypeVarMap( decl->type );
2285        return scrubAllTypeVars( decl );
2286}
2287
2288ast::FunctionDecl const * Eraser::previsit( ast::FunctionDecl const * decl ) {
2289        guardTypeVarMap( decl->type );
2290        return scrubAllTypeVars( decl );
2291}
2292
2293ast::FunctionDecl const * Eraser::postvisit( ast::FunctionDecl const * decl ) {
2294        if ( decl->type_params.empty() ) return decl;
2295        auto mutDecl = mutate( decl );
2296        mutDecl->type_params.clear();
2297        return mutDecl;
2298}
2299
2300ast::TypedefDecl const * Eraser::previsit( ast::TypedefDecl const * decl ) {
2301        guardTypeVarMap( decl->base );
2302        return scrubAllTypeVars( decl );
2303}
2304
2305/// Strips the members from a generic aggregate.
2306template<typename node_t>
2307node_t const * stripGenericMembers( node_t const * decl ) {
2308        if ( decl->params.empty() ) return decl;
2309        auto mutDecl = ast::mutate( decl );
2310        mutDecl->members.clear();
2311        return mutDecl;
2312}
2313
2314ast::StructDecl const * Eraser::previsit( ast::StructDecl const * decl ) {
2315        return stripGenericMembers( decl );
2316}
2317
2318ast::UnionDecl const * Eraser::previsit( ast::UnionDecl const * decl ) {
2319        return stripGenericMembers( decl );
2320}
2321
2322void Eraser::previsit( ast::TypeDecl const * decl ) {
2323        addToTypeVarMap( decl, scopeTypeVars );
2324}
2325
2326void Eraser::previsit( ast::PointerType const * type ) {
2327        guardTypeVarMap( type );
2328}
2329
2330void Eraser::previsit( ast::FunctionType const * type ) {
2331        guardTypeVarMap( type );
2332}
2333
2334} // namespace
2335
2336// --------------------------------------------------------------------------
2337void box( ast::TranslationUnit & translationUnit ) {
2338        ast::Pass<LayoutFunctionBuilder>::run( translationUnit );
2339        ast::Pass<CallAdapter>::run( translationUnit );
2340        ast::Pass<DeclAdapter>::run( translationUnit );
2341        ast::Pass<RewireAdapters>::run( translationUnit );
2342        ast::Pass<PolyGenericCalculator>::run( translationUnit );
2343        ast::Pass<Eraser>::run( translationUnit );
2344}
2345
2346} // namespace GenPoly
2347
2348// Local Variables: //
2349// tab-width: 4 //
2350// mode: c++ //
2351// compile-command: "make install" //
2352// End: //
Note: See TracBrowser for help on using the repository browser.