Move PREFERRED_DEBUGGING_TYPE define in pa64-hpux.h to pa.h
[official-gcc.git] / gcc / d / decl.cc
blob0d46ee180e75d52774dbb10d3cac58cc1e573451
1 /* decl.cc -- Lower D frontend declarations to GCC trees.
2 Copyright (C) 2006-2021 Free Software Foundation, Inc.
4 GCC is free software; you can redistribute it and/or modify
5 it under the terms of the GNU General Public License as published by
6 the Free Software Foundation; either version 3, or (at your option)
7 any later version.
9 GCC is distributed in the hope that it will be useful,
10 but WITHOUT ANY WARRANTY; without even the implied warranty of
11 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 GNU General Public License for more details.
14 You should have received a copy of the GNU General Public License
15 along with GCC; see the file COPYING3. If not see
16 <http://www.gnu.org/licenses/>. */
18 #include "config.h"
19 #include "system.h"
20 #include "coretypes.h"
22 #include "dmd/aggregate.h"
23 #include "dmd/attrib.h"
24 #include "dmd/cond.h"
25 #include "dmd/ctfe.h"
26 #include "dmd/declaration.h"
27 #include "dmd/enum.h"
28 #include "dmd/errors.h"
29 #include "dmd/globals.h"
30 #include "dmd/hdrgen.h"
31 #include "dmd/identifier.h"
32 #include "dmd/import.h"
33 #include "dmd/init.h"
34 #include "dmd/mangle.h"
35 #include "dmd/module.h"
36 #include "dmd/nspace.h"
37 #include "dmd/target.h"
38 #include "dmd/template.h"
40 #include "tree.h"
41 #include "tree-iterator.h"
42 #include "fold-const.h"
43 #include "diagnostic.h"
44 #include "langhooks.h"
45 #include "target.h"
46 #include "common/common-target.h"
47 #include "cgraph.h"
48 #include "toplev.h"
49 #include "stringpool.h"
50 #include "varasm.h"
51 #include "stor-layout.h"
52 #include "attribs.h"
53 #include "function.h"
54 #include "debug.h"
55 #include "tree-pretty-print.h"
56 #include "tree-nested.h"
57 #include "alloc-pool.h"
58 #include "symbol-summary.h"
59 #include "symtab-thunks.h"
61 #include "d-tree.h"
62 #include "d-target.h"
65 /* Return identifier for the external mangled name of DECL. */
67 const char *
68 d_mangle_decl (Dsymbol *decl)
70 if (decl->isFuncDeclaration ())
71 return mangleExact ((FuncDeclaration *) decl);
72 else
74 OutBuffer buf;
75 mangleToBuffer (decl, &buf);
76 return buf.extractChars ();
80 /* Generate a mangled identifier using NAME and SUFFIX, prefixed by the
81 assembler name for DECL. */
83 tree
84 mangle_internal_decl (Dsymbol *decl, const char *name, const char *suffix)
86 const char *prefix = d_mangle_decl (decl);
87 unsigned namelen = strlen (name);
88 unsigned buflen = (2 + strlen (prefix) + namelen + strlen (suffix)) * 2;
89 char *buf = (char *) alloca (buflen);
91 snprintf (buf, buflen, "_D%s%u%s%s", prefix, namelen, name, suffix);
92 tree ident = get_identifier (buf);
94 /* Symbol is not found in user code, but generate a readable name for it
95 anyway for debug and diagnostic reporting. */
96 snprintf (buf, buflen, "%s.%s", decl->toPrettyChars (), name);
97 IDENTIFIER_PRETTY_NAME (ident) = get_identifier (buf);
99 return ident;
102 /* Returns true if DECL is from the gcc.attribute module. */
104 static bool
105 gcc_attribute_p (Dsymbol *decl)
107 ModuleDeclaration *md = decl->getModule ()->md;
109 if (md && md->packages && md->packages->length == 1)
111 if (!strcmp ((*md->packages)[0]->toChars (), "gcc")
112 && !strcmp (md->id->toChars (), "attributes"))
113 return true;
116 return false;
119 /* Implements the visitor interface to lower all Declaration AST classes
120 emitted from the D Front-end to GCC trees.
121 All visit methods accept one parameter D, which holds the frontend AST
122 of the declaration to compile. These also don't return any value, instead
123 generated code are appened to global_declarations or added to the
124 current_binding_level by d_pushdecl(). */
126 class DeclVisitor : public Visitor
128 using Visitor::visit;
130 /* If we're lowering the body of a version(unittest) condition. */
131 bool in_version_unittest_;
133 public:
134 DeclVisitor (void)
136 this->in_version_unittest_ = false;
139 /* Helper for generating code for the dsymbol AST class D.
140 Sets up the location of the symbol before lowering. */
142 void build_dsymbol (Dsymbol *d)
144 location_t saved_location = input_location;
145 input_location = make_location_t (d->loc);
146 d->accept (this);
147 input_location = saved_location;
150 /* This should be overridden by each declaration class. */
152 void visit (Dsymbol *)
156 /* Compile a D module, and all members of it. */
158 void visit (Module *d)
160 if (d->semanticRun >= PASSobj)
161 return;
163 build_module_tree (d);
164 d->semanticRun = PASSobj;
167 /* Write the imported symbol to debug. */
169 void visit (Import *d)
171 if (d->semanticRun >= PASSobj)
172 return;
174 /* Implements import declarations by telling the debug back-end we are
175 importing the NAMESPACE_DECL of the module or IMPORTED_DECL of the
176 declaration into the current lexical scope CONTEXT. NAME is set if
177 this is a renamed import. */
178 if (d->isstatic)
179 return;
181 /* Get the context of this import, this should never be null. */
182 tree context = d_module_context ();
184 if (d->ident == NULL)
186 /* Importing declaration list. */
187 for (size_t i = 0; i < d->names.length; i++)
189 AliasDeclaration *aliasdecl = d->aliasdecls[i];
190 tree decl = build_import_decl (aliasdecl);
192 /* Skip over unhandled imports. */
193 if (decl == NULL_TREE)
194 continue;
196 Identifier *alias = d->aliases[i];
197 tree name = (alias != NULL)
198 ? get_identifier (alias->toChars ()) : NULL_TREE;
200 debug_hooks->imported_module_or_decl (decl, name, context,
201 false, false);
204 else
206 /* Importing the entire module. */
207 tree decl = build_import_decl (d->mod);
209 tree name = (d->aliasId != NULL)
210 ? get_identifier (d->aliasId->toChars ()) : NULL_TREE;
212 debug_hooks->imported_module_or_decl (decl, name, context,
213 false, false);
216 d->semanticRun = PASSobj;
219 /* Expand any local variables found in tuples. */
221 void visit (TupleDeclaration *d)
223 for (size_t i = 0; i < d->objects->length; i++)
225 RootObject *o = (*d->objects)[i];
226 if (o->dyncast () == DYNCAST_EXPRESSION)
228 DsymbolExp *de = ((Expression *) o)->isDsymbolExp ();
229 if (de != NULL && de->s->isDeclaration ())
230 this->build_dsymbol (de->s);
235 /* Walk over all declarations in the attribute scope. */
237 void visit (AttribDeclaration *d)
239 Dsymbols *ds = d->include (NULL);
241 if (!ds)
242 return;
244 for (size_t i = 0; i < ds->length; i++)
245 this->build_dsymbol ((*ds)[i]);
248 /* Pragmas are a way to pass special information to the compiler and to add
249 vendor specific extensions to D. We don't do anything here, yet. */
251 void visit (PragmaDeclaration *d)
253 if (!global.params.ignoreUnsupportedPragmas)
255 if (d->ident == Identifier::idPool ("lib")
256 || d->ident == Identifier::idPool ("startaddress"))
258 warning_at (make_location_t (d->loc), OPT_Wunknown_pragmas,
259 "pragma(%s) not implemented", d->ident->toChars ());
263 visit ((AttribDeclaration *) d);
266 /* Conditional compilation is the process of selecting which code to compile
267 and which code to not compile. Look for version conditions that may */
269 void visit (ConditionalDeclaration *d)
271 bool old_condition = this->in_version_unittest_;
273 if (global.params.useUnitTests)
275 VersionCondition *vc = d->condition->isVersionCondition ();
276 if (vc && vc->ident == Identifier::idPool ("unittest"))
277 this->in_version_unittest_ = true;
280 visit ((AttribDeclaration *) d);
282 this->in_version_unittest_ = old_condition;
285 /* Walk over all members in the namespace scope. */
287 void visit (Nspace *d)
289 if (isError (d) || !d->members)
290 return;
292 for (size_t i = 0; i < d->members->length; i++)
293 this->build_dsymbol ((*d->members)[i]);
296 /* Templates are D's approach to generic programming. They have no members
297 that can be emitted, however if the template is nested and used as a
298 voldemort type, then it's members must be compiled before the parent
299 function finishes. */
301 void visit (TemplateDeclaration *d)
303 /* Type cannot be directly named outside of the scope it's declared in, so
304 the only way it can be escaped is if the function has auto return. */
305 FuncDeclaration *fd = d_function_chain ? d_function_chain->function : NULL;
307 if (!fd || !fd->isAuto ())
308 return;
310 /* Check if the function returns an instantiated type that may contain
311 nested members. Only applies to classes or structs. */
312 Type *tb = fd->type->nextOf ()->baseElemOf ();
314 while (tb->ty == Tarray || tb->ty == Tpointer)
315 tb = tb->nextOf ()->baseElemOf ();
317 TemplateInstance *ti = NULL;
319 if (tb->ty == Tstruct)
320 ti = tb->isTypeStruct ()->sym->isInstantiated ();
321 else if (tb->ty == Tclass)
322 ti = tb->isTypeClass ()->sym->isInstantiated ();
324 /* Return type is instantiated from this template declaration, walk over
325 all members of the instance. */
326 if (ti && ti->tempdecl == d)
327 this->build_dsymbol (ti);
330 /* Walk over all members in the instantiated template. */
332 void visit (TemplateInstance *d)
334 if (isError (d)|| !d->members)
335 return;
337 if (!d->needsCodegen ())
338 return;
340 for (size_t i = 0; i < d->members->length; i++)
341 this->build_dsymbol ((*d->members)[i]);
344 /* Walk over all members in the mixin template scope. */
346 void visit (TemplateMixin *d)
348 if (isError (d)|| !d->members)
349 return;
351 for (size_t i = 0; i < d->members->length; i++)
352 this->build_dsymbol ((*d->members)[i]);
355 /* Write out compiler generated TypeInfo, initializer and functions for the
356 given struct declaration, walking over all static members. */
358 void visit (StructDeclaration *d)
360 if (d->semanticRun >= PASSobj)
361 return;
363 if (d->type->ty == Terror)
365 error_at (make_location_t (d->loc),
366 "had semantic errors when compiling");
367 return;
370 /* Add this decl to the current binding level. */
371 tree ctype = build_ctype (d->type);
372 if (TYPE_NAME (ctype))
373 d_pushdecl (TYPE_NAME (ctype));
375 /* Anonymous structs/unions only exist as part of others,
376 do not output forward referenced structs. */
377 if (d->isAnonymous () || !d->members)
378 return;
380 /* Don't emit any symbols from gcc.attribute module. */
381 if (gcc_attribute_p (d))
382 return;
384 /* Generate TypeInfo. */
385 if (have_typeinfo_p (Type::dtypeinfo))
386 create_typeinfo (d->type, NULL);
388 /* Generate static initializer. */
389 tree sinit = aggregate_initializer_decl (d);
390 DECL_INITIAL (sinit) = layout_struct_initializer (d);
391 d_finish_decl (sinit);
393 /* Put out the members. There might be static constructors in the members
394 list, and they cannot be put in separate object files. */
395 for (size_t i = 0; i < d->members->length; i++)
396 this->build_dsymbol ((*d->members)[i]);
398 /* Put out xopEquals, xopCmp and xopHash. */
399 if (d->xeq && d->xeq != d->xerreq)
400 this->build_dsymbol (d->xeq);
402 if (d->xcmp && d->xcmp != d->xerrcmp)
403 this->build_dsymbol (d->xcmp);
405 if (d->xhash)
406 this->build_dsymbol (d->xhash);
408 d->semanticRun = PASSobj;
411 /* Finish semantic analysis of functions in vtbl for class CD. */
413 bool finish_vtable (ClassDeclaration *d)
415 bool has_errors = false;
417 /* Finish semantic analysis of functions in vtbl[]. */
418 for (size_t i = d->vtblOffset (); i < d->vtbl.length; i++)
420 FuncDeclaration *fd = d->vtbl[i]->isFuncDeclaration ();
422 if (!fd || (!fd->fbody && d->isAbstract ()))
423 continue;
425 /* Ensure function has a return value. */
426 if (!fd->functionSemantic ())
427 has_errors = true;
429 /* No name hiding to check for. */
430 if (!d->isFuncHidden (fd) || fd->isFuture ())
431 continue;
433 /* The function fd is hidden from the view of the class.
434 If it overlaps with any function in the vtbl[], then
435 issue an error. */
436 for (size_t j = 1; j < d->vtbl.length; j++)
438 if (j == i)
439 continue;
441 FuncDeclaration *fd2 = d->vtbl[j]->isFuncDeclaration ();
442 if (!fd2->ident->equals (fd->ident))
443 continue;
445 /* The function is marked as @__future, a deprecation has
446 already been given by the frontend. */
447 if (fd2->isFuture ())
448 continue;
450 if (fd->leastAsSpecialized (fd2) || fd2->leastAsSpecialized (fd))
452 error_at (make_location_t (fd->loc), "use of %qs",
453 fd->toPrettyChars ());
454 inform (make_location_t (fd2->loc), "is hidden by %qs",
455 fd2->toPrettyChars ());
456 inform (make_location_t (d->loc),
457 "use %<alias %s = %s.%s;%> to introduce base class "
458 "overload set", fd->toChars (),
459 fd->parent->toChars (), fd->toChars ());
460 has_errors = true;
461 break;
466 return !has_errors;
469 /* Write out compiler generated TypeInfo, initializer and vtables for the
470 given class declaration, walking over all static members. */
472 void visit (ClassDeclaration *d)
474 if (d->semanticRun >= PASSobj)
475 return;
477 if (d->type->ty == Terror)
479 error_at (make_location_t (d->loc),
480 "had semantic errors when compiling");
481 return;
484 if (!d->members)
485 return;
487 /* Put out the members. */
488 for (size_t i = 0; i < d->members->length; i++)
489 this->build_dsymbol ((*d->members)[i]);
491 /* If something goes wrong during final semantic pass, don't bother with
492 the rest as we may have incomplete info. */
493 if (!this->finish_vtable (d))
494 return;
496 /* Generate C symbols. */
497 d->csym = get_classinfo_decl (d);
498 d->vtblsym = get_vtable_decl (d);
499 tree sinit = aggregate_initializer_decl (d);
501 /* Generate static initializer. */
502 DECL_INITIAL (sinit) = layout_class_initializer (d);
503 d_finish_decl (sinit);
505 /* Put out the TypeInfo. */
506 if (have_typeinfo_p (Type::dtypeinfo))
507 create_typeinfo (d->type, NULL);
509 DECL_INITIAL (d->csym) = layout_classinfo (d);
510 d_finish_decl (d->csym);
512 /* Put out the vtbl[]. */
513 vec <constructor_elt, va_gc> *elms = NULL;
515 /* First entry is ClassInfo reference. */
516 if (d->vtblOffset ())
517 CONSTRUCTOR_APPEND_ELT (elms, size_zero_node, build_address (d->csym));
519 for (size_t i = d->vtblOffset (); i < d->vtbl.length; i++)
521 FuncDeclaration *fd = d->vtbl[i]->isFuncDeclaration ();
523 if (fd && (fd->fbody || !d->isAbstract ()))
525 CONSTRUCTOR_APPEND_ELT (elms, size_int (i),
526 build_address (get_symbol_decl (fd)));
530 DECL_INITIAL (d->vtblsym)
531 = build_constructor (TREE_TYPE (d->vtblsym), elms);
532 d_finish_decl (d->vtblsym);
534 /* Add this decl to the current binding level. */
535 tree ctype = TREE_TYPE (build_ctype (d->type));
536 if (TYPE_NAME (ctype))
537 d_pushdecl (TYPE_NAME (ctype));
539 d->semanticRun = PASSobj;
542 /* Write out compiler generated TypeInfo and vtables for the given interface
543 declaration, walking over all static members. */
545 void visit (InterfaceDeclaration *d)
547 if (d->semanticRun >= PASSobj)
548 return;
550 if (d->type->ty == Terror)
552 error_at (make_location_t (d->loc),
553 "had semantic errors when compiling");
554 return;
557 if (!d->members)
558 return;
560 /* Put out the members. */
561 for (size_t i = 0; i < d->members->length; i++)
562 this->build_dsymbol ((*d->members)[i]);
564 /* Generate C symbols. */
565 d->csym = get_classinfo_decl (d);
567 /* Put out the TypeInfo. */
568 if (have_typeinfo_p (Type::dtypeinfo))
570 create_typeinfo (d->type, NULL);
571 this->build_dsymbol (d->type->vtinfo);
574 DECL_INITIAL (d->csym) = layout_classinfo (d);
575 d_finish_decl (d->csym);
577 /* Add this decl to the current binding level. */
578 tree ctype = TREE_TYPE (build_ctype (d->type));
579 if (TYPE_NAME (ctype))
580 d_pushdecl (TYPE_NAME (ctype));
582 d->semanticRun = PASSobj;
585 /* Write out compiler generated TypeInfo and initializer for the given
586 enum declaration. */
588 void visit (EnumDeclaration *d)
590 if (d->semanticRun >= PASSobj)
591 return;
593 if (d->errors || d->type->ty == Terror)
595 error_at (make_location_t (d->loc),
596 "had semantic errors when compiling");
597 return;
600 if (d->isAnonymous ())
601 return;
603 /* Generate TypeInfo. */
604 if (have_typeinfo_p (Type::dtypeinfo))
605 create_typeinfo (d->type, NULL);
607 TypeEnum *tc = d->type->isTypeEnum ();
608 if (tc->sym->members && !d->type->isZeroInit ())
610 /* Generate static initializer. */
611 d->sinit = enum_initializer_decl (d);
612 DECL_INITIAL (d->sinit) = build_expr (tc->sym->defaultval, true);
613 d_finish_decl (d->sinit);
616 /* Add this decl to the current binding level. */
617 tree ctype = build_ctype (d->type);
618 if (TYPE_NAME (ctype))
619 d_pushdecl (TYPE_NAME (ctype));
621 d->semanticRun = PASSobj;
624 /* Finish up a variable declaration and push it into the current scope.
625 This can either be a static, local or manifest constant. */
627 void visit (VarDeclaration *d)
629 if (d->semanticRun >= PASSobj)
630 return;
632 if (d->type->ty == Terror)
634 error_at (make_location_t (d->loc),
635 "had semantic errors when compiling");
636 return;
639 if (d->aliassym)
641 this->build_dsymbol (d->toAlias ());
642 return;
645 if (!d->canTakeAddressOf ())
647 /* Do not store variables we cannot take the address of,
648 but keep the values for purposes of debugging. */
649 if (!d->type->isscalar ())
651 tree decl = get_symbol_decl (d);
652 d_pushdecl (decl);
653 rest_of_decl_compilation (decl, 1, 0);
656 else if (d->isDataseg () && !(d->storage_class & STCextern))
658 tree decl = get_symbol_decl (d);
660 /* Duplicated VarDeclarations map to the same symbol. Check if this
661 is the one declaration which will be emitted. */
662 tree ident = DECL_ASSEMBLER_NAME (decl);
663 if (IDENTIFIER_DSYMBOL (ident) && IDENTIFIER_DSYMBOL (ident) != d)
664 return;
666 /* How big a symbol can be should depend on back-end. */
667 tree size = build_integer_cst (d->type->size (d->loc),
668 build_ctype (Type::tsize_t));
669 if (!valid_constant_size_p (size))
671 error_at (make_location_t (d->loc), "size is too large");
672 return;
675 if (d->_init)
677 /* Use the explicit initializer, this includes `void`. */
678 if (!d->_init->isVoidInitializer ())
680 Expression *e = initializerToExpression (d->_init, d->type);
681 DECL_INITIAL (decl) = build_expr (e, true);
684 else
686 /* Use default initializer for the type. */
687 if (TypeStruct *ts = d->type->isTypeStruct ())
688 DECL_INITIAL (decl) = layout_struct_initializer (ts->sym);
689 else
691 Expression *e = d->type->defaultInitLiteral (d->loc);
692 DECL_INITIAL (decl) = build_expr (e, true);
696 /* Frontend should have already caught this. */
697 gcc_assert (!integer_zerop (size)
698 || d->type->toBasetype ()->ty == Tsarray);
700 d_finish_decl (decl);
702 /* Maybe record the var against the current module. */
703 register_module_decl (d);
705 else if (!d->isDataseg () && !d->isMember ())
707 /* This is needed for VarDeclarations in mixins that are to be local
708 variables of a function. Otherwise, it would be enough to make
709 a check for isVarDeclaration() in DeclarationExp codegen. */
710 declare_local_var (d);
712 if (d->_init && !d->_init->isVoidInitializer ())
714 tree decl = get_symbol_decl (d);
716 ExpInitializer *vinit = d->_init->isExpInitializer ();
717 Expression *ie = initializerToExpression (vinit);
718 tree exp = build_expr (ie);
720 /* Maybe put variable on list of things needing destruction. */
721 if (d->needsScopeDtor ())
723 vec_safe_push (d_function_chain->vars_in_scope, decl);
724 /* Force a TARGET_EXPR to add the corresponding cleanup. */
725 exp = force_target_expr (compound_expr (exp, decl));
726 TARGET_EXPR_CLEANUP (exp) = build_expr (d->edtor);
729 add_stmt (exp);
733 d->semanticRun = PASSobj;
736 /* Generate and compile a static TypeInfo declaration, but only if it is
737 needed in the current compilation. */
739 void visit (TypeInfoDeclaration *d)
741 if (d->semanticRun >= PASSobj)
742 return;
744 if (speculative_type_p (d->tinfo))
745 return;
747 tree t = get_typeinfo_decl (d);
748 DECL_INITIAL (t) = layout_typeinfo (d);
749 d_finish_decl (t);
750 d->semanticRun = PASSobj;
753 /* Finish up a function declaration and compile it all the way
754 down to assembler language output. */
756 void visit (FuncDeclaration *d)
758 /* Already generated the function. */
759 if (d->semanticRun >= PASSobj)
760 return;
762 /* Don't emit any symbols from gcc.attribute module. */
763 if (gcc_attribute_p (d))
764 return;
766 /* Not emitting unittest functions. */
767 if (!global.params.useUnitTests && d->isUnitTestDeclaration ())
768 return;
770 /* Check if any errors occurred when running semantic. */
771 if (TypeFunction *tf = d->type->isTypeFunction ())
773 if (tf->next == NULL || tf->next->ty == Terror)
774 return;
777 if (d->semantic3Errors)
778 return;
780 if (d->isNested ())
782 FuncDeclaration *fdp = d;
783 while (fdp && fdp->isNested ())
785 fdp = fdp->toParent2 ()->isFuncDeclaration ();
787 if (fdp == NULL)
788 break;
790 /* Parent failed to compile, but errors were gagged. */
791 if (fdp->semantic3Errors)
792 return;
796 /* Ensure all semantic passes have run. */
797 if (d->semanticRun < PASSsemantic3)
799 d->functionSemantic3 ();
800 Module::runDeferredSemantic3 ();
803 if (global.errors)
804 return;
806 /* Duplicated FuncDeclarations map to the same symbol. Check if this
807 is the one declaration which will be emitted. */
808 tree fndecl = get_symbol_decl (d);
809 tree ident = DECL_ASSEMBLER_NAME (fndecl);
810 if (IDENTIFIER_DSYMBOL (ident) && IDENTIFIER_DSYMBOL (ident) != d)
811 return;
813 if (!d->fbody)
815 rest_of_decl_compilation (fndecl, 1, 0);
816 return;
819 if (global.params.verbose)
820 message ("function %s", d->toPrettyChars ());
822 /* Start generating code for this function. */
823 gcc_assert (d->semanticRun == PASSsemantic3done);
824 d->semanticRun = PASSobj;
826 tree old_context = start_function (d);
828 tree parm_decl = NULL_TREE;
829 tree param_list = NULL_TREE;
831 /* Special arguments... */
833 /* `this' parameter:
834 For nested functions, D still generates a vthis, but it
835 should not be referenced in any expression. */
836 if (d->vthis)
838 parm_decl = get_symbol_decl (d->vthis);
839 DECL_ARTIFICIAL (parm_decl) = 1;
840 TREE_READONLY (parm_decl) = 1;
842 if (d->vthis->type == Type::tvoidptr)
844 /* Replace generic pointer with back-end closure type
845 (this wins for gdb). */
846 tree frame_type = FRAMEINFO_TYPE (get_frameinfo (d));
847 gcc_assert (frame_type != NULL_TREE);
848 TREE_TYPE (parm_decl) = build_pointer_type (frame_type);
851 param_list = chainon (param_list, parm_decl);
852 d_function_chain->static_chain = parm_decl;
855 /* _arguments parameter. */
856 if (d->v_arguments)
858 parm_decl = get_symbol_decl (d->v_arguments);
859 param_list = chainon (param_list, parm_decl);
862 /* formal function parameters. */
863 size_t n_parameters = d->parameters ? d->parameters->length : 0;
865 for (size_t i = 0; i < n_parameters; i++)
867 VarDeclaration *param = (*d->parameters)[i];
868 parm_decl = get_symbol_decl (param);
869 /* Chain them in the correct order. */
870 param_list = chainon (param_list, parm_decl);
873 DECL_ARGUMENTS (fndecl) = param_list;
874 DECL_IN_UNITTEST_CONDITION_P (fndecl) = this->in_version_unittest_;
875 rest_of_decl_compilation (fndecl, 1, 0);
877 /* If this is a member function that nested (possibly indirectly) in another
878 function, construct an expession for this member function's static chain
879 by going through parent link of nested classes. */
880 if (d->isThis ())
882 AggregateDeclaration *ad = d->isThis ();
883 tree this_tree = get_symbol_decl (d->vthis);
885 while (ad->isNested ())
887 Dsymbol *pd = ad->toParent2 ();
888 tree vthis_field = get_symbol_decl (ad->vthis);
889 this_tree = component_ref (build_deref (this_tree), vthis_field);
891 ad = pd->isAggregateDeclaration ();
892 if (ad == NULL)
894 cfun->language->static_chain = this_tree;
895 break;
900 /* May change cfun->static_chain. */
901 build_closure (d);
903 if (d->vresult)
904 declare_local_var (d->vresult);
906 if (d->v_argptr)
907 push_stmt_list ();
909 /* Named return value optimisation support for D.
910 Implemented by overriding all the RETURN_EXPRs and replacing all
911 occurrences of VAR with the RESULT_DECL for the function.
912 This is only worth doing for functions that can return in memory. */
913 tree resdecl = DECL_RESULT (fndecl);
915 if (TREE_ADDRESSABLE (TREE_TYPE (resdecl))
916 || aggregate_value_p (TREE_TYPE (resdecl), fndecl))
918 /* Return non-trivial structs by invisible reference. */
919 if (TREE_ADDRESSABLE (TREE_TYPE (resdecl)))
921 TREE_TYPE (resdecl) = build_reference_type (TREE_TYPE (resdecl));
922 DECL_BY_REFERENCE (resdecl) = 1;
923 TREE_ADDRESSABLE (resdecl) = 0;
924 relayout_decl (resdecl);
925 d->shidden = build_deref (resdecl);
927 else
928 d->shidden = resdecl;
930 if (d->nrvo_can && d->nrvo_var)
932 tree var = get_symbol_decl (d->nrvo_var);
934 /* Copy name from VAR to RESULT. */
935 DECL_NAME (resdecl) = DECL_NAME (var);
936 /* Don't forget that we take its address. */
937 TREE_ADDRESSABLE (var) = 1;
939 SET_DECL_VALUE_EXPR (var, resdecl);
940 DECL_HAS_VALUE_EXPR_P (var) = 1;
941 SET_DECL_LANG_NRVO (var, d->shidden);
945 build_function_body (d);
947 /* Initialize the _argptr variable. */
948 if (d->v_argptr)
950 tree body = pop_stmt_list ();
951 tree var = get_decl_tree (d->v_argptr);
952 var = build_address (var);
954 tree init = build_call_expr (builtin_decl_explicit (BUILT_IN_VA_START),
955 2, var, parm_decl);
956 declare_local_var (d->v_argptr);
957 add_stmt (init);
959 tree cleanup = build_call_expr (builtin_decl_explicit (BUILT_IN_VA_END),
960 1, var);
961 add_stmt (build2 (TRY_FINALLY_EXPR, void_type_node, body, cleanup));
964 finish_function (old_context);
966 /* Maybe record the function against the current module. */
967 register_module_decl (d);
971 /* Main entry point for the DeclVisitor interface to send
972 the Declaration AST class D to GCC back-end. */
974 void
975 build_decl_tree (Dsymbol *d)
977 location_t saved_location = input_location;
979 /* Set input location, empty DECL_SOURCE_FILE can crash debug generator. */
980 if (d->loc.filename)
981 input_location = make_location_t (d->loc);
982 else
983 input_location = make_location_t (Loc ("<no_file>", 1, 0));
985 DeclVisitor v = DeclVisitor ();
986 v.build_dsymbol (d);
988 input_location = saved_location;
991 /* Return the decl for the symbol, create it if it doesn't already exist. */
993 tree
994 get_symbol_decl (Declaration *decl)
996 if (decl->csym)
997 return decl->csym;
999 /* Deal with placeholder symbols immediately:
1000 SymbolDeclaration is used as a shell around an initializer symbol. */
1001 SymbolDeclaration *sd = decl->isSymbolDeclaration ();
1002 if (sd)
1004 decl->csym = aggregate_initializer_decl (sd->dsym);
1005 return decl->csym;
1008 /* Global static TypeInfo declaration. */
1009 if (decl->isTypeInfoDeclaration ())
1010 return get_typeinfo_decl ((TypeInfoDeclaration *) decl);
1012 /* FuncAliasDeclaration is used to import functions from another scope. */
1013 FuncAliasDeclaration *fad = decl->isFuncAliasDeclaration ();
1014 if (fad)
1016 decl->csym = get_symbol_decl (fad->funcalias);
1017 return decl->csym;
1020 /* It is possible for a field declaration symbol to be requested
1021 before the parent type has been built. */
1022 if (decl->isField ())
1024 AggregateDeclaration *ad = decl->toParent ()->isAggregateDeclaration ();
1025 gcc_assert (ad != NULL);
1027 /* Finishing off the type should create the associated FIELD_DECL. */
1028 build_ctype (ad->type);
1029 gcc_assert (decl->csym != NULL);
1031 return decl->csym;
1034 /* Build the tree for the symbol. */
1035 FuncDeclaration *fd = decl->isFuncDeclaration ();
1036 if (fd)
1038 /* Run full semantic on functions we need to know about. */
1039 if (!fd->functionSemantic ())
1041 decl->csym = error_mark_node;
1042 return decl->csym;
1045 decl->csym = build_decl (make_location_t (decl->loc), FUNCTION_DECL,
1046 get_identifier (decl->ident->toChars ()),
1047 NULL_TREE);
1049 /* Set function type afterwards as there could be self references. */
1050 TREE_TYPE (decl->csym) = build_ctype (fd->type);
1052 /* Set DECL_INITIAL now if the function has a definition. */
1053 if (fd->fbody)
1054 DECL_INITIAL (decl->csym) = error_mark_node;
1055 else
1056 DECL_EXTERNAL (decl->csym) = 1;
1058 else
1060 /* Build the variable declaration. */
1061 VarDeclaration *vd = decl->isVarDeclaration ();
1062 gcc_assert (vd != NULL);
1064 tree_code code = vd->isParameter () ? PARM_DECL
1065 : !vd->canTakeAddressOf () ? CONST_DECL
1066 : VAR_DECL;
1067 decl->csym = build_decl (make_location_t (decl->loc), code,
1068 get_identifier (decl->ident->toChars ()),
1069 declaration_type (vd));
1071 /* If any alignment was set on the declaration. */
1072 if (vd->alignment != STRUCTALIGN_DEFAULT)
1074 SET_DECL_ALIGN (decl->csym, vd->alignment * BITS_PER_UNIT);
1075 DECL_USER_ALIGN (decl->csym) = 1;
1078 if (vd->storage_class & STCextern)
1079 DECL_EXTERNAL (decl->csym) = 1;
1081 /* CONST_DECL was initially intended for enumerals and may be used for
1082 scalars in general, but not for aggregates. Here a non-constant
1083 value is generated anyway so as the CONST_DECL only serves as a
1084 placeholder for the value, however the DECL itself should never be
1085 referenced in any generated code, or passed to the back-end. */
1086 if (vd->storage_class & STCmanifest)
1088 /* Cannot make an expression out of a void initializer. */
1089 if (vd->_init && !vd->_init->isVoidInitializer ())
1091 Expression *ie = initializerToExpression (vd->_init);
1093 if (!vd->type->isscalar ())
1094 DECL_INITIAL (decl->csym) = build_expr (ie, false);
1095 else
1096 DECL_INITIAL (decl->csym) = build_expr (ie, true);
1101 /* Set the declaration mangled identifier if static. */
1102 if (decl->isCodeseg () || decl->isDataseg ())
1104 tree mangled_name;
1106 if (decl->mangleOverride.length)
1108 mangled_name =
1109 get_identifier_with_length (decl->mangleOverride.ptr,
1110 decl->mangleOverride.length);
1112 else
1113 mangled_name = get_identifier (d_mangle_decl (decl));
1115 mangled_name = targetm.mangle_decl_assembler_name (decl->csym,
1116 mangled_name);
1117 /* The frontend doesn't handle duplicate definitions of unused symbols
1118 with the same mangle. So a check is done here instead. */
1119 if (IDENTIFIER_DSYMBOL (mangled_name))
1121 Declaration *other = IDENTIFIER_DSYMBOL (mangled_name);
1122 tree olddecl = decl->csym;
1123 decl->csym = get_symbol_decl (other);
1125 /* Update the symbol location to the current definition. */
1126 if (DECL_EXTERNAL (decl->csym) && !DECL_INITIAL (decl->csym))
1127 DECL_SOURCE_LOCATION (decl->csym) = DECL_SOURCE_LOCATION (olddecl);
1129 /* The current declaration is a prototype or marked extern, merge
1130 applied user attributes and return. */
1131 if (DECL_EXTERNAL (olddecl) && !DECL_INITIAL (olddecl))
1133 apply_user_attributes (decl, decl->csym);
1134 return decl->csym;
1136 /* The previous declaration is a prototype or marked extern, set the
1137 current declaration as the main reference of the symbol. */
1138 else if (DECL_EXTERNAL (decl->csym) && !DECL_INITIAL (decl->csym))
1140 IDENTIFIER_DSYMBOL (mangled_name) = decl;
1141 DECL_EXTERNAL (decl->csym) = 0;
1143 /* Non-extern, non-templated decls shouldn't be defined twice. */
1144 else if (!decl->isInstantiated ())
1145 ScopeDsymbol::multiplyDefined (decl->loc, decl, other);
1147 else
1149 IDENTIFIER_PRETTY_NAME (mangled_name)
1150 = get_identifier (decl->toPrettyChars (true));
1151 IDENTIFIER_DSYMBOL (mangled_name) = decl;
1153 SET_DECL_ASSEMBLER_NAME (decl->csym, mangled_name);
1157 DECL_LANG_SPECIFIC (decl->csym) = build_lang_decl (decl);
1158 DECL_CONTEXT (decl->csym) = d_decl_context (decl);
1160 if (TREE_CODE (decl->csym) == PARM_DECL)
1162 /* Pass non-trivial structs by invisible reference. */
1163 if (TREE_ADDRESSABLE (TREE_TYPE (decl->csym)))
1165 tree argtype = build_reference_type (TREE_TYPE (decl->csym));
1166 argtype = build_qualified_type (argtype, TYPE_QUAL_RESTRICT);
1167 gcc_assert (!DECL_BY_REFERENCE (decl->csym));
1168 TREE_TYPE (decl->csym) = argtype;
1169 DECL_BY_REFERENCE (decl->csym) = 1;
1170 TREE_ADDRESSABLE (decl->csym) = 0;
1171 relayout_decl (decl->csym);
1172 decl->storage_class |= STCref;
1175 DECL_ARG_TYPE (decl->csym) = TREE_TYPE (decl->csym);
1176 gcc_assert (TREE_CODE (DECL_CONTEXT (decl->csym)) == FUNCTION_DECL);
1178 else if (TREE_CODE (decl->csym) == CONST_DECL)
1180 /* Manifest constants have no address in memory. */
1181 TREE_CONSTANT (decl->csym) = 1;
1182 TREE_READONLY (decl->csym) = 1;
1184 else if (TREE_CODE (decl->csym) == FUNCTION_DECL)
1186 /* The real function type may differ from its declaration. */
1187 tree fntype = TREE_TYPE (decl->csym);
1188 tree newfntype = NULL_TREE;
1190 if (fd->isNested ())
1192 /* Add an extra argument for the frame/closure pointer, this is also
1193 required to be compatible with D delegates. */
1194 newfntype = build_vthis_function (void_type_node, fntype);
1196 else if (fd->isThis ())
1198 /* Add an extra argument for the `this' parameter. The handle type is
1199 used even if there is no debug info. It is needed to make sure
1200 virtual member functions are not called statically. */
1201 AggregateDeclaration *ad = fd->isMember2 ();
1202 tree handle = build_ctype (ad->handleType ());
1204 /* If handle is a pointer type, get record type. */
1205 if (!ad->isStructDeclaration ())
1206 handle = TREE_TYPE (handle);
1208 newfntype = build_vthis_function (handle, fntype);
1210 /* Set the vindex on virtual functions. */
1211 if (fd->isVirtual () && fd->vtblIndex != -1)
1213 DECL_VINDEX (decl->csym) = size_int (fd->vtblIndex);
1214 DECL_VIRTUAL_P (decl->csym) = 1;
1217 else if (fd->isMain () || fd->isCMain ())
1219 /* The main function is named `D main' to distinguish from C main. */
1220 if (fd->isMain ())
1221 DECL_NAME (decl->csym) = get_identifier (fd->toPrettyChars (true));
1223 /* `void main' is implicitly converted to returning an int. */
1224 newfntype = build_function_type (d_int_type, TYPE_ARG_TYPES (fntype));
1227 if (newfntype != NULL_TREE)
1229 /* Copy the old attributes from the original type. */
1230 TYPE_ATTRIBUTES (newfntype) = TYPE_ATTRIBUTES (fntype);
1231 TYPE_LANG_SPECIFIC (newfntype) = TYPE_LANG_SPECIFIC (fntype);
1232 TREE_ADDRESSABLE (newfntype) = TREE_ADDRESSABLE (fntype);
1233 TREE_TYPE (decl->csym) = newfntype;
1234 d_keep (newfntype);
1237 /* Miscellaneous function flags. */
1239 /* In [pragma/inline], functions decorated with `pragma(inline)' affects
1240 whether they are inlined or not. */
1241 if (fd->inlining == PINLINEalways)
1242 DECL_DECLARED_INLINE_P (decl->csym) = 1;
1243 else if (fd->inlining == PINLINEnever)
1244 DECL_UNINLINABLE (decl->csym) = 1;
1246 /* Function was declared `naked'. */
1247 if (fd->naked)
1249 insert_decl_attribute (decl->csym, "naked");
1250 DECL_NO_INSTRUMENT_FUNCTION_ENTRY_EXIT (decl->csym) = 1;
1253 /* Mark compiler generated functions as artificial. */
1254 if (fd->generated)
1255 DECL_ARTIFICIAL (decl->csym) = 1;
1257 /* Vector array operations are always compiler generated. */
1258 if (fd->isArrayOp)
1260 DECL_ARTIFICIAL (decl->csym) = 1;
1261 DECL_DECLARED_INLINE_P (decl->csym) = 1;
1264 /* Ensure and require contracts are lexically nested in the function they
1265 part of, but are always publicly callable. */
1266 if (fd->ident == Identifier::idPool ("ensure")
1267 || fd->ident == Identifier::idPool ("require"))
1268 TREE_PUBLIC (decl->csym) = 1;
1270 if (decl->storage_class & STCfinal)
1271 DECL_FINAL_P (decl->csym) = 1;
1273 /* Function is of type `noreturn' or `typeof(*null)'. */
1274 if (fd->type->nextOf ()->ty == Tnoreturn)
1275 TREE_THIS_VOLATILE (decl->csym) = 1;
1277 /* Check whether this function is expanded by the frontend. */
1278 DECL_INTRINSIC_CODE (decl->csym) = INTRINSIC_NONE;
1279 maybe_set_intrinsic (fd);
1281 /* For nested functions in particular, unnest fndecl in the cgraph, as
1282 all static chain passing is handled by the front-end. Do this even
1283 if we are not emitting the body. */
1284 struct cgraph_node *node = cgraph_node::get_create (decl->csym);
1285 if (nested_function_origin (node))
1286 unnest_function (node);
1289 /* Mark compiler generated temporaries as artificial. */
1290 if (decl->storage_class & STCtemp)
1291 DECL_ARTIFICIAL (decl->csym) = 1;
1293 /* Propagate shared on the decl. */
1294 if (TYPE_SHARED (TREE_TYPE (decl->csym)))
1295 TREE_ADDRESSABLE (decl->csym) = 1;
1297 /* Symbol was marked volatile. */
1298 if (decl->storage_class & STCvolatile)
1299 TREE_THIS_VOLATILE (decl->csym) = 1;
1301 /* Protection attributes are used by the debugger. */
1302 if (decl->protection.kind == Prot::private_)
1303 TREE_PRIVATE (decl->csym) = 1;
1304 else if (decl->protection.kind == Prot::protected_)
1305 TREE_PROTECTED (decl->csym) = 1;
1307 /* Likewise, so could the deprecated attribute. */
1308 if (decl->storage_class & STCdeprecated)
1309 TREE_DEPRECATED (decl->csym) = 1;
1311 #if TARGET_DLLIMPORT_DECL_ATTRIBUTES
1312 /* Have to test for import first. */
1313 if (decl->isImportedSymbol ())
1315 insert_decl_attribute (decl->csym, "dllimport");
1316 DECL_DLLIMPORT_P (decl->csym) = 1;
1318 else if (decl->isExport ())
1319 insert_decl_attribute (decl->csym, "dllexport");
1320 #endif
1322 if (decl->isDataseg () || decl->isCodeseg () || decl->isThreadlocal ())
1324 /* Set TREE_PUBLIC by default, but allow private template to override. */
1325 if (!fd || !fd->isNested ())
1326 TREE_PUBLIC (decl->csym) = 1;
1328 TREE_STATIC (decl->csym) = 1;
1329 /* The decl has not been defined -- yet. */
1330 DECL_EXTERNAL (decl->csym) = 1;
1332 DECL_INSTANTIATED (decl->csym) = (decl->isInstantiated () != NULL);
1333 set_linkage_for_decl (decl->csym);
1336 /* Symbol is going in thread local storage. */
1337 if (decl->isThreadlocal () && !DECL_ARTIFICIAL (decl->csym))
1339 if (global.params.vtls)
1340 message (decl->loc, "`%s` is thread local", decl->toChars ());
1342 set_decl_tls_model (decl->csym, decl_default_tls_model (decl->csym));
1345 /* Apply any user attributes that may affect semantic meaning. */
1346 apply_user_attributes (decl, decl->csym);
1348 /* %% Probably should be a little more intelligent about setting this. */
1349 TREE_USED (decl->csym) = 1;
1350 d_keep (decl->csym);
1352 return decl->csym;
1355 /* Returns a declaration for a VAR_DECL. Used to create compiler-generated
1356 global variables. */
1358 tree
1359 declare_extern_var (tree ident, tree type)
1361 /* If the VAR_DECL has already been declared, return it. */
1362 if (IDENTIFIER_DECL_TREE (ident))
1363 return IDENTIFIER_DECL_TREE (ident);
1365 tree name = IDENTIFIER_PRETTY_NAME (ident)
1366 ? IDENTIFIER_PRETTY_NAME (ident) : ident;
1367 tree decl = build_decl (input_location, VAR_DECL, name, type);
1369 IDENTIFIER_DECL_TREE (ident) = decl;
1370 d_keep (decl);
1372 SET_DECL_ASSEMBLER_NAME (decl, ident);
1373 DECL_ARTIFICIAL (decl) = 1;
1374 TREE_STATIC (decl) = 1;
1375 TREE_PUBLIC (decl) = 1;
1377 /* The decl has not been defined -- yet. */
1378 DECL_EXTERNAL (decl) = 1;
1380 set_linkage_for_decl (decl);
1382 return decl;
1385 /* Add local variable VAR into the current function body. */
1387 void
1388 declare_local_var (VarDeclaration *var)
1390 gcc_assert (!var->isDataseg () && !var->isMember ());
1391 gcc_assert (current_function_decl != NULL_TREE);
1393 FuncDeclaration *fd = cfun->language->function;
1394 tree decl = get_symbol_decl (var);
1396 gcc_assert (!TREE_STATIC (decl));
1397 d_pushdecl (decl);
1398 DECL_CONTEXT (decl) = current_function_decl;
1400 /* Compiler generated symbols. */
1401 if (var == fd->vresult || var == fd->v_argptr)
1402 DECL_ARTIFICIAL (decl) = 1;
1404 if (DECL_LANG_FRAME_FIELD (decl))
1406 /* Fixes debugging local variables. */
1407 SET_DECL_VALUE_EXPR (decl, get_decl_tree (var));
1408 DECL_HAS_VALUE_EXPR_P (decl) = 1;
1412 /* Return an unnamed local temporary of type TYPE. */
1414 tree
1415 build_local_temp (tree type)
1417 tree decl = build_decl (input_location, VAR_DECL, NULL_TREE, type);
1419 DECL_CONTEXT (decl) = current_function_decl;
1420 DECL_ARTIFICIAL (decl) = 1;
1421 DECL_IGNORED_P (decl) = 1;
1422 d_pushdecl (decl);
1424 return decl;
1427 /* Return the correct decl to be used for DECL. For VAR_DECLs, this could
1428 instead be a FIELD_DECL from a closure, or a RESULT_DECL from a named return
1429 value. For PARM_DECLs, this could be a FIELD_DECL for a non-local `this'.
1430 For all other kinds of decls, this just returns the result of
1431 get_symbol_decl(). */
1433 tree
1434 get_decl_tree (Declaration *decl)
1436 tree t = get_symbol_decl (decl);
1437 FuncDeclaration *fd = cfun ? cfun->language->function : NULL;
1438 VarDeclaration *vd = decl->isVarDeclaration ();
1440 /* If cfun is NULL, then this is a global static. */
1441 if (vd == NULL || fd == NULL)
1442 return t;
1444 /* Get the named return value. */
1445 if (DECL_LANG_NRVO (t))
1446 return DECL_LANG_NRVO (t);
1448 /* Get the closure holding the var decl. */
1449 if (DECL_LANG_FRAME_FIELD (t))
1451 FuncDeclaration *parent = vd->toParent2 ()->isFuncDeclaration ();
1452 tree frame_ref = get_framedecl (fd, parent);
1454 return component_ref (build_deref (frame_ref),
1455 DECL_LANG_FRAME_FIELD (t));
1458 /* Get the non-local `this' value by going through parent link
1459 of nested classes, this routine pretty much undoes what
1460 getRightThis in the frontend removes from codegen. */
1461 if (vd->parent != fd && vd->isThisDeclaration ())
1463 /* Find the first parent that is a member function. */
1464 while (!fd->isMember2 ())
1466 gcc_assert (fd->vthis);
1467 fd = fd->toParent2 ()->isFuncDeclaration ();
1468 gcc_assert (fd != NULL);
1471 AggregateDeclaration *ad = fd->isThis ();
1472 gcc_assert (ad != NULL);
1474 /* The parent function is for the same `this' declaration we are
1475 building a chain to. Non-local declaration is inaccessible. */
1476 if (fd->vthis == vd)
1477 return error_no_frame_access (fd);
1479 t = get_decl_tree (fd->vthis);
1480 Dsymbol *outer = fd;
1482 while (outer != vd->parent)
1484 gcc_assert (ad != NULL);
1485 outer = ad->toParent2 ();
1487 /* Get the this->this parent link. */
1488 tree vfield = get_symbol_decl (ad->vthis);
1489 t = component_ref (build_deref (t), vfield);
1491 ad = outer->isAggregateDeclaration ();
1492 if (ad != NULL)
1493 continue;
1495 fd = outer->isFuncDeclaration ();
1496 while (fd != NULL)
1498 /* If outer function creates a closure, then the `this'
1499 value would be the closure pointer, and the real
1500 `this' the first field of that closure. */
1501 tree ff = get_frameinfo (fd);
1502 if (FRAMEINFO_CREATES_FRAME (ff))
1504 t = build_nop (build_pointer_type (FRAMEINFO_TYPE (ff)), t);
1505 t = indirect_ref (build_ctype (fd->vthis->type), t);
1508 if (fd == vd->parent)
1509 break;
1511 /* Continue looking for the right `this'. */
1512 outer = outer->toParent2 ();
1513 fd = outer->isFuncDeclaration ();
1516 ad = outer->isAggregateDeclaration ();
1519 return t;
1522 /* Auto variable that the back end will handle for us. */
1523 return t;
1526 /* Finish up a variable declaration and compile it all the way to
1527 the assembler language output. */
1529 void
1530 d_finish_decl (tree decl)
1532 gcc_assert (!error_operand_p (decl));
1534 /* We are sending this symbol to object file, can't be extern. */
1535 TREE_STATIC (decl) = 1;
1536 DECL_EXTERNAL (decl) = 0;
1538 /* Update the TLS model as the linkage has been modified. */
1539 if (DECL_THREAD_LOCAL_P (decl))
1540 set_decl_tls_model (decl, decl_default_tls_model (decl));
1542 relayout_decl (decl);
1544 if (flag_checking && DECL_INITIAL (decl))
1546 /* Initializer must never be bigger than symbol size. */
1547 dinteger_t tsize = int_size_in_bytes (TREE_TYPE (decl));
1548 dinteger_t dtsize = int_size_in_bytes (TREE_TYPE (DECL_INITIAL (decl)));
1550 if (tsize < dtsize)
1552 tree name = DECL_ASSEMBLER_NAME (decl);
1554 internal_error ("Mismatch between declaration %qE size (%wd) and "
1555 "its initializer size (%wd).",
1556 IDENTIFIER_PRETTY_NAME (name)
1557 ? IDENTIFIER_PRETTY_NAME (name) : name,
1558 tsize, dtsize);
1562 /* Without weak symbols, symbol should be put in .common, but that can't
1563 be done if there is a nonzero initializer. */
1564 if (DECL_COMDAT (decl) && DECL_COMMON (decl)
1565 && initializer_zerop (DECL_INITIAL (decl)))
1566 DECL_INITIAL (decl) = error_mark_node;
1568 /* Add this decl to the current binding level. */
1569 d_pushdecl (decl);
1571 rest_of_decl_compilation (decl, 1, 0);
1574 /* Thunk code is based on g++. */
1576 static int thunk_labelno;
1578 /* Create a static alias to function. */
1580 static tree
1581 make_alias_for_thunk (tree function)
1583 tree alias;
1584 char buf[256];
1586 /* Thunks may reference extern functions which cannot be aliased. */
1587 if (DECL_EXTERNAL (function))
1588 return function;
1590 targetm.asm_out.generate_internal_label (buf, "LTHUNK", thunk_labelno);
1591 thunk_labelno++;
1593 alias = build_decl (DECL_SOURCE_LOCATION (function), FUNCTION_DECL,
1594 get_identifier (buf), TREE_TYPE (function));
1595 DECL_LANG_SPECIFIC (alias) = DECL_LANG_SPECIFIC (function);
1596 lang_hooks.dup_lang_specific_decl (alias);
1597 DECL_CONTEXT (alias) = NULL_TREE;
1598 TREE_READONLY (alias) = TREE_READONLY (function);
1599 TREE_THIS_VOLATILE (alias) = TREE_THIS_VOLATILE (function);
1600 TREE_PUBLIC (alias) = 0;
1602 DECL_EXTERNAL (alias) = 0;
1603 DECL_ARTIFICIAL (alias) = 1;
1605 DECL_DECLARED_INLINE_P (alias) = 0;
1606 DECL_INITIAL (alias) = error_mark_node;
1607 DECL_ARGUMENTS (alias) = copy_list (DECL_ARGUMENTS (function));
1609 TREE_ADDRESSABLE (alias) = 1;
1610 TREE_USED (alias) = 1;
1611 SET_DECL_ASSEMBLER_NAME (alias, DECL_NAME (alias));
1613 if (!flag_syntax_only)
1615 cgraph_node *aliasn;
1616 aliasn = cgraph_node::create_same_body_alias (alias, function);
1617 gcc_assert (aliasn != NULL);
1619 return alias;
1622 /* Emit the definition of a D vtable thunk. */
1624 static void
1625 finish_thunk (tree thunk, tree function)
1627 /* Setup how D thunks are outputted. */
1628 int fixed_offset = -THUNK_LANG_OFFSET (thunk);
1629 bool this_adjusting = true;
1630 tree alias;
1632 if (TARGET_USE_LOCAL_THUNK_ALIAS_P (function))
1633 alias = make_alias_for_thunk (function);
1634 else
1635 alias = function;
1637 TREE_ADDRESSABLE (function) = 1;
1638 TREE_USED (function) = 1;
1640 if (flag_syntax_only)
1642 TREE_ASM_WRITTEN (thunk) = 1;
1643 return;
1646 if (TARGET_USE_LOCAL_THUNK_ALIAS_P (function)
1647 && targetm_common.have_named_sections)
1649 tree fn = function;
1650 symtab_node *symbol = symtab_node::get (function);
1652 if (symbol != NULL && symbol->alias)
1654 if (symbol->analyzed)
1655 fn = symtab_node::get (function)->ultimate_alias_target ()->decl;
1656 else
1657 fn = symtab_node::get (function)->alias_target;
1659 resolve_unique_section (fn, 0, flag_function_sections);
1661 if (DECL_SECTION_NAME (fn) != NULL && DECL_ONE_ONLY (fn))
1663 resolve_unique_section (thunk, 0, flag_function_sections);
1665 /* Output the thunk into the same section as function. */
1666 set_decl_section_name (thunk, fn);
1667 symtab_node::get (thunk)->implicit_section
1668 = symtab_node::get (fn)->implicit_section;
1672 /* Set up cloned argument trees for the thunk. */
1673 tree t = NULL_TREE;
1674 for (tree a = DECL_ARGUMENTS (function); a; a = DECL_CHAIN (a))
1676 tree x = copy_node (a);
1677 DECL_CHAIN (x) = t;
1678 DECL_CONTEXT (x) = thunk;
1679 SET_DECL_RTL (x, NULL);
1680 DECL_HAS_VALUE_EXPR_P (x) = 0;
1681 TREE_ADDRESSABLE (x) = 0;
1682 t = x;
1684 DECL_ARGUMENTS (thunk) = nreverse (t);
1685 TREE_ASM_WRITTEN (thunk) = 1;
1687 cgraph_node *funcn, *thunk_node;
1689 funcn = cgraph_node::get_create (function);
1690 gcc_assert (funcn);
1691 thunk_node = funcn->create_thunk (thunk, thunk, this_adjusting,
1692 fixed_offset, 0, 0, 0, alias);
1694 if (DECL_ONE_ONLY (function))
1695 thunk_node->add_to_same_comdat_group (funcn);
1698 /* Return a thunk to DECL. Thunks adjust the incoming `this' pointer by OFFSET.
1699 Adjustor thunks are created and pointers to them stored in the method entries
1700 in the vtable in order to set the this pointer to the start of the object
1701 instance corresponding to the implementing method. */
1703 tree
1704 make_thunk (FuncDeclaration *decl, int offset)
1706 tree function = get_symbol_decl (decl);
1708 if (!DECL_ARGUMENTS (function) || !DECL_RESULT (function))
1710 /* Compile the function body before generating the thunk, this is done
1711 even if the decl is external to the current module. */
1712 if (decl->fbody)
1713 build_decl_tree (decl);
1714 else
1716 /* Build parameters for functions that are not being compiled,
1717 so that they can be correctly cloned in finish_thunk. */
1718 tree fntype = TREE_TYPE (function);
1719 tree params = NULL_TREE;
1721 for (tree t = TYPE_ARG_TYPES (fntype); t; t = TREE_CHAIN (t))
1723 if (t == void_list_node)
1724 break;
1726 tree param = build_decl (DECL_SOURCE_LOCATION (function),
1727 PARM_DECL, NULL_TREE, TREE_VALUE (t));
1728 DECL_ARG_TYPE (param) = TREE_TYPE (param);
1729 DECL_ARTIFICIAL (param) = 1;
1730 DECL_IGNORED_P (param) = 1;
1731 DECL_CONTEXT (param) = function;
1732 params = chainon (params, param);
1735 DECL_ARGUMENTS (function) = params;
1737 /* Also build the result decl, which is needed when force creating
1738 the thunk in gimple inside cgraph_node::expand_thunk. */
1739 tree resdecl = build_decl (DECL_SOURCE_LOCATION (function),
1740 RESULT_DECL, NULL_TREE,
1741 TREE_TYPE (fntype));
1742 DECL_ARTIFICIAL (resdecl) = 1;
1743 DECL_IGNORED_P (resdecl) = 1;
1744 DECL_CONTEXT (resdecl) = function;
1745 DECL_RESULT (function) = resdecl;
1749 /* Don't build the thunk if the compilation step failed. */
1750 if (global.errors)
1751 return error_mark_node;
1753 /* See if we already have the thunk in question. */
1754 for (tree t = DECL_LANG_THUNKS (function); t; t = DECL_CHAIN (t))
1756 if (THUNK_LANG_OFFSET (t) == offset)
1757 return t;
1760 tree thunk = build_decl (DECL_SOURCE_LOCATION (function),
1761 FUNCTION_DECL, NULL_TREE, TREE_TYPE (function));
1762 DECL_LANG_SPECIFIC (thunk) = DECL_LANG_SPECIFIC (function);
1763 lang_hooks.dup_lang_specific_decl (thunk);
1764 THUNK_LANG_OFFSET (thunk) = offset;
1766 TREE_READONLY (thunk) = TREE_READONLY (function);
1767 TREE_THIS_VOLATILE (thunk) = TREE_THIS_VOLATILE (function);
1768 TREE_NOTHROW (thunk) = TREE_NOTHROW (function);
1770 DECL_CONTEXT (thunk) = d_decl_context (decl);
1772 /* Thunks inherit the public access of the function they are targeting.
1773 Thunks are connected to the definitions of the functions, so thunks are
1774 not produced for external functions. */
1775 TREE_PUBLIC (thunk) = TREE_PUBLIC (function);
1776 DECL_EXTERNAL (thunk) = DECL_EXTERNAL (function);
1778 /* Thunks are always addressable. */
1779 TREE_ADDRESSABLE (thunk) = 1;
1780 TREE_USED (thunk) = 1;
1781 DECL_ARTIFICIAL (thunk) = 1;
1782 DECL_DECLARED_INLINE_P (thunk) = 0;
1784 if (TREE_PUBLIC (thunk))
1786 DECL_VISIBILITY (thunk) = DECL_VISIBILITY (function);
1787 DECL_COMDAT (thunk) = DECL_COMDAT (function);
1788 DECL_WEAK (thunk) = DECL_WEAK (function);
1791 /* When the thunk is for an extern C++ function, let C++ do the thunk
1792 generation and just reference the symbol as extern, instead of
1793 forcing a D local thunk to be emitted. */
1794 const char *ident;
1796 if (decl->linkage == LINKcpp)
1797 ident = target.cpp.thunkMangle (decl, offset);
1798 else
1800 tree target_name = DECL_ASSEMBLER_NAME (function);
1801 unsigned identlen = IDENTIFIER_LENGTH (target_name) + 14;
1802 ident = XNEWVEC (const char, identlen);
1804 snprintf (CONST_CAST (char *, ident), identlen,
1805 "_DTi%u%s", offset, IDENTIFIER_POINTER (target_name));
1808 DECL_NAME (thunk) = get_identifier (ident);
1809 SET_DECL_ASSEMBLER_NAME (thunk, DECL_NAME (thunk));
1811 d_keep (thunk);
1812 free (CONST_CAST (char *, ident));
1814 if (!DECL_EXTERNAL (function))
1815 finish_thunk (thunk, function);
1817 /* Add it to the list of thunks associated with the function. */
1818 DECL_LANG_THUNKS (thunk) = NULL_TREE;
1819 DECL_CHAIN (thunk) = DECL_LANG_THUNKS (function);
1820 DECL_LANG_THUNKS (function) = thunk;
1822 return thunk;
1825 /* Create the FUNCTION_DECL for a function definition.
1826 This function creates a binding context for the function body
1827 as well as setting up the FUNCTION_DECL in current_function_decl.
1828 Returns the previous function context if it was already set. */
1830 tree
1831 start_function (FuncDeclaration *fd)
1833 tree fndecl = get_symbol_decl (fd);
1835 /* Function has been defined, check now whether we intend to send it to
1836 object file, or it really is extern. Such as inlinable functions from
1837 modules not in this compilation, or thunk aliases. */
1838 TemplateInstance *ti = fd->isInstantiated ();
1839 if (ti && ti->needsCodegen ())
1841 /* Warn about templates instantiated in this compilation. */
1842 if (ti == fd->parent)
1844 warning (OPT_Wtemplates, "%s %qs instantiated",
1845 ti->kind (), ti->toPrettyChars (false));
1848 DECL_EXTERNAL (fndecl) = 0;
1850 else
1852 Module *md = fd->getModule ();
1853 if (md && md->isRoot ())
1854 DECL_EXTERNAL (fndecl) = 0;
1857 DECL_INITIAL (fndecl) = error_mark_node;
1859 /* Add this decl to the current binding level. */
1860 d_pushdecl (fndecl);
1862 /* Save the current function context. */
1863 tree old_context = current_function_decl;
1865 if (old_context)
1866 push_function_context ();
1868 /* Let GCC know the current scope is this function. */
1869 current_function_decl = fndecl;
1871 tree restype = TREE_TYPE (TREE_TYPE (fndecl));
1872 tree resdecl = build_decl (make_location_t (fd->loc), RESULT_DECL,
1873 NULL_TREE, restype);
1875 DECL_RESULT (fndecl) = resdecl;
1876 DECL_CONTEXT (resdecl) = fndecl;
1877 DECL_ARTIFICIAL (resdecl) = 1;
1878 DECL_IGNORED_P (resdecl) = 1;
1880 /* Initialize the RTL code for the function. */
1881 allocate_struct_function (fndecl, false);
1883 /* Store the end of the function. */
1884 if (fd->endloc.filename)
1885 cfun->function_end_locus = make_location_t (fd->endloc);
1886 else
1887 cfun->function_end_locus = DECL_SOURCE_LOCATION (fndecl);
1889 cfun->language = ggc_cleared_alloc <language_function> ();
1890 cfun->language->function = fd;
1892 /* Default chain value is `null' unless parent found. */
1893 cfun->language->static_chain = null_pointer_node;
1895 /* Find module for this function. */
1896 for (Dsymbol *p = fd->parent; p != NULL; p = p->parent)
1898 cfun->language->module = p->isModule ();
1899 if (cfun->language->module)
1900 break;
1902 gcc_assert (cfun->language->module != NULL);
1904 /* Begin the statement tree for this function. */
1905 push_stmt_list ();
1906 push_binding_level (level_function);
1908 return old_context;
1911 /* Finish up a function declaration and compile that function all
1912 the way to assembler language output. The free the storage for
1913 the function definition. Restores the previous function context. */
1915 void
1916 finish_function (tree old_context)
1918 tree fndecl = current_function_decl;
1920 /* Tie off the statement tree for this function. */
1921 tree block = pop_binding_level ();
1922 tree body = pop_stmt_list ();
1923 tree bind = build3 (BIND_EXPR, void_type_node,
1924 BLOCK_VARS (block), body, block);
1926 gcc_assert (vec_safe_is_empty (d_function_chain->stmt_list));
1928 /* Back-end expects a statement list to come from somewhere, however
1929 pop_stmt_list returns expressions when there is a single statement.
1930 So here we create a statement list unconditionally. */
1931 if (TREE_CODE (body) != STATEMENT_LIST)
1933 tree stmtlist = alloc_stmt_list ();
1934 append_to_statement_list_force (body, &stmtlist);
1935 BIND_EXPR_BODY (bind) = stmtlist;
1937 else if (!STATEMENT_LIST_HEAD (body))
1939 /* For empty functions add a void return. */
1940 append_to_statement_list_force (return_expr (NULL_TREE), &body);
1943 DECL_SAVED_TREE (fndecl) = bind;
1945 if (!errorcount && !global.errors)
1947 /* Dump the D-specific tree IR. */
1948 dump_function (TDI_original, fndecl);
1950 cgraph_node::finalize_function (fndecl, true);
1953 /* We're leaving the context of this function, so free it. */
1954 ggc_free (cfun->language);
1955 cfun->language = NULL;
1956 set_cfun (NULL);
1958 if (old_context)
1959 pop_function_context ();
1961 current_function_decl = old_context;
1964 /* Mark DECL, which is a VAR_DECL or FUNCTION_DECL as a symbol that
1965 must be emitted in this, output module. */
1967 static void
1968 d_mark_needed (tree decl)
1970 TREE_USED (decl) = 1;
1972 if (TREE_CODE (decl) == FUNCTION_DECL)
1974 struct cgraph_node *node = cgraph_node::get_create (decl);
1975 node->forced_by_abi = true;
1977 else if (VAR_P (decl))
1979 struct varpool_node *node = varpool_node::get_create (decl);
1980 node->forced_by_abi = true;
1984 /* Get the VAR_DECL of the vtable symbol for DECL. If this does not yet exist,
1985 create it. The vtable is accessible via ClassInfo, but since it is needed
1986 frequently (like for rtti comparisons), make it directly accessible. */
1988 tree
1989 get_vtable_decl (ClassDeclaration *decl)
1991 if (decl->vtblsym)
1992 return decl->vtblsym;
1994 tree ident = mangle_internal_decl (decl, "__vtbl", "Z");
1995 /* Note: Using a static array type for the VAR_DECL, the DECL_INITIAL value
1996 will have a different type. However the back-end seems to accept this. */
1997 tree type = build_ctype (Type::tvoidptr->sarrayOf (decl->vtbl.length));
1999 decl->vtblsym = declare_extern_var (ident, type);
2000 DECL_LANG_SPECIFIC (decl->vtblsym) = build_lang_decl (NULL);
2002 /* Class is a reference, want the record type. */
2003 DECL_CONTEXT (decl->vtblsym) = TREE_TYPE (build_ctype (decl->type));
2004 TREE_READONLY (decl->vtblsym) = 1;
2005 DECL_VIRTUAL_P (decl->vtblsym) = 1;
2007 SET_DECL_ALIGN (decl->vtblsym, TARGET_VTABLE_ENTRY_ALIGN);
2008 DECL_USER_ALIGN (decl->vtblsym) = true;
2010 return decl->vtblsym;
2013 /* Helper function of build_class_instance. Find the field inside aggregate
2014 TYPE identified by IDENT at field OFFSET. */
2016 static tree
2017 find_aggregate_field (tree type, tree ident, tree offset)
2019 tree fields = TYPE_FIELDS (type);
2021 for (tree field = fields; field != NULL_TREE; field = TREE_CHAIN (field))
2023 if (DECL_NAME (field) == NULL_TREE
2024 && RECORD_OR_UNION_TYPE_P (TREE_TYPE (field))
2025 && ANON_AGGR_TYPE_P (TREE_TYPE (field)))
2027 /* Search nesting anonymous structs and unions. */
2028 tree vfield = find_aggregate_field (TREE_TYPE (field),
2029 ident, offset);
2030 if (vfield != NULL_TREE)
2031 return vfield;
2033 else if (DECL_NAME (field) == ident
2034 && (offset == NULL_TREE
2035 || DECL_FIELD_OFFSET (field) == offset))
2037 /* Found matching field at offset. */
2038 return field;
2042 return NULL_TREE;
2045 /* Helper function of build_new_class_expr. Return a constructor that matches
2046 the layout of the class expression EXP. */
2048 static tree
2049 build_class_instance (ClassReferenceExp *exp)
2051 ClassDeclaration *cd = exp->originalClass ();
2052 tree type = TREE_TYPE (build_ctype (exp->value->stype));
2053 vec <constructor_elt, va_gc> *ve = NULL;
2055 /* The set base vtable field. */
2056 tree vptr = build_address (get_vtable_decl (cd));
2057 CONSTRUCTOR_APPEND_ELT (ve, TYPE_FIELDS (type), vptr);
2059 /* Go through the inheritance graph from top to bottom. This will add all
2060 values to the constructor out of order, however build_struct_literal
2061 will re-order all values before returning the finished literal. */
2062 for (ClassDeclaration *bcd = cd; bcd != NULL; bcd = bcd->baseClass)
2064 /* Anonymous vtable interface fields are laid out before the fields of
2065 each class. The interface offset is used to determine where to put
2066 the classinfo offset reference. */
2067 for (size_t i = 0; i < bcd->vtblInterfaces->length; i++)
2069 BaseClass *bc = (*bcd->vtblInterfaces)[i];
2071 for (ClassDeclaration *cd2 = cd; 1; cd2 = cd2->baseClass)
2073 gcc_assert (cd2 != NULL);
2075 unsigned csymoffset = base_vtable_offset (cd2, bc);
2076 /* If the base class vtable was found. */
2077 if (csymoffset != ~0u)
2079 tree csym = build_address (get_classinfo_decl (cd2));
2080 csym = build_offset (csym, size_int (csymoffset));
2082 tree field = find_aggregate_field (type, NULL_TREE,
2083 size_int (bc->offset));
2084 gcc_assert (field != NULL_TREE);
2086 CONSTRUCTOR_APPEND_ELT (ve, field, csym);
2087 break;
2092 /* Generate initial values of all fields owned by current class.
2093 Use both the name and offset to find the right field. */
2094 for (size_t i = 0; i < bcd->fields.length; i++)
2096 VarDeclaration *vfield = bcd->fields[i];
2097 int index = exp->findFieldIndexByName (vfield);
2098 gcc_assert (index != -1);
2100 Expression *value = (*exp->value->elements)[index];
2101 if (!value)
2102 continue;
2104 /* Use find_aggregate_field to get the overridden field decl,
2105 instead of the field associated with the base class. */
2106 tree field = get_symbol_decl (bcd->fields[i]);
2107 field = find_aggregate_field (type, DECL_NAME (field),
2108 DECL_FIELD_OFFSET (field));
2109 gcc_assert (field != NULL_TREE);
2111 CONSTRUCTOR_APPEND_ELT (ve, field, build_expr (value, true));
2115 return build_struct_literal (type, ve);
2118 /* Get the VAR_DECL of a class instance representing EXPR as static data.
2119 If this does not yet exist, create it. This is used to support initializing
2120 a static variable that is of a class type using values known during CTFE.
2121 In user code, it is analogous to the following code snippet.
2123 enum E = new C(1, 2, 3);
2125 That we write the contents of `C(1, 2, 3)' to static data is only a compiler
2126 implementation detail. The initialization of these symbols could be done at
2127 run-time using during as part of the module initialization or shared static
2128 constructors phase of run-time start-up - whichever comes after `gc_init()'.
2129 And infact that would be the better thing to do here eventually. */
2131 tree
2132 build_new_class_expr (ClassReferenceExp *expr)
2134 if (expr->value->sym)
2135 return expr->value->sym;
2137 /* Build the reference symbol. */
2138 tree type = build_ctype (expr->value->stype);
2139 expr->value->sym = build_artificial_decl (TREE_TYPE (type), NULL_TREE, "C");
2141 DECL_INITIAL (expr->value->sym) = build_class_instance (expr);
2142 d_pushdecl (expr->value->sym);
2143 rest_of_decl_compilation (expr->value->sym, 1, 0);
2145 return expr->value->sym;
2148 /* Get the VAR_DECL of the static initializer symbol for the struct/class DECL.
2149 If this does not yet exist, create it. The static initializer data is
2150 accessible via TypeInfo, and is also used in `new class' and default
2151 initializing struct literals. */
2153 tree
2154 aggregate_initializer_decl (AggregateDeclaration *decl)
2156 if (decl->sinit)
2157 return (tree) decl->sinit;
2159 /* Class is a reference, want the record type. */
2160 tree type = build_ctype (decl->type);
2161 StructDeclaration *sd = decl->isStructDeclaration ();
2162 if (!sd)
2163 type = TREE_TYPE (type);
2165 tree ident = mangle_internal_decl (decl, "__init", "Z");
2167 tree sinit = declare_extern_var (ident, type);
2168 DECL_LANG_SPECIFIC (sinit) = build_lang_decl (NULL);
2170 DECL_CONTEXT (sinit) = type;
2171 TREE_READONLY (sinit) = 1;
2173 /* Honor struct alignment set by user. */
2174 if (sd && sd->alignment != STRUCTALIGN_DEFAULT)
2176 SET_DECL_ALIGN (sinit, sd->alignment * BITS_PER_UNIT);
2177 DECL_USER_ALIGN (sinit) = true;
2180 decl->sinit = sinit;
2181 return sinit;
2184 /* Generate the data for the static initializer. */
2186 tree
2187 layout_class_initializer (ClassDeclaration *cd)
2189 NewExp *ne = NewExp::create (cd->loc, NULL, NULL, cd->type, NULL);
2190 ne->type = cd->type;
2192 Expression *e = ne->ctfeInterpret ();
2193 gcc_assert (e->op == TOKclassreference);
2195 return build_class_instance (e->isClassReferenceExp ());
2198 tree
2199 layout_struct_initializer (StructDeclaration *sd)
2201 StructLiteralExp *sle = StructLiteralExp::create (sd->loc, sd, NULL);
2203 if (!sd->fill (sd->loc, sle->elements, true))
2204 gcc_unreachable ();
2206 sle->type = sd->type;
2207 return build_expr (sle, true);
2210 /* Get the VAR_DECL of the static initializer symbol for the enum DECL.
2211 If this does not yet exist, create it. The static initializer data is
2212 accessible via TypeInfo_Enum, but the field member type is a byte[] that
2213 requires a pointer to a symbol reference. */
2215 tree
2216 enum_initializer_decl (EnumDeclaration *decl)
2218 if (decl->sinit)
2219 return decl->sinit;
2221 gcc_assert (decl->ident);
2223 tree type = build_ctype (decl->type);
2224 tree ident = mangle_internal_decl (decl, "__init", "Z");
2226 decl->sinit = declare_extern_var (ident, type);
2227 DECL_LANG_SPECIFIC (decl->sinit) = build_lang_decl (NULL);
2229 DECL_CONTEXT (decl->sinit) = d_decl_context (decl);
2230 TREE_READONLY (decl->sinit) = 1;
2232 return decl->sinit;
2235 /* Return an anonymous static variable of type TYPE, initialized with INIT,
2236 and optionally prefixing the name with PREFIX. */
2238 tree
2239 build_artificial_decl (tree type, tree init, const char *prefix)
2241 tree decl = build_decl (UNKNOWN_LOCATION, VAR_DECL, NULL_TREE, type);
2242 const char *name = prefix ? prefix : "___s";
2243 char *label;
2245 ASM_FORMAT_PRIVATE_NAME (label, name, DECL_UID (decl));
2246 SET_DECL_ASSEMBLER_NAME (decl, get_identifier (label));
2247 DECL_NAME (decl) = DECL_ASSEMBLER_NAME (decl);
2249 TREE_PUBLIC (decl) = 0;
2250 TREE_STATIC (decl) = 1;
2251 TREE_USED (decl) = 1;
2252 DECL_IGNORED_P (decl) = 1;
2253 DECL_ARTIFICIAL (decl) = 1;
2255 /* Perhaps at some point the initializer constant should be hashed
2256 to remove duplicates. */
2257 DECL_INITIAL (decl) = init;
2259 return decl;
2262 /* Build TYPE_DECL for the declaration DSYM. */
2264 void
2265 build_type_decl (tree type, Dsymbol *dsym)
2267 if (TYPE_STUB_DECL (type))
2268 return;
2270 /* If a templated type, use the template instance name, as that includes all
2271 template parameters. */
2272 const char *name = dsym->parent->isTemplateInstance ()
2273 ? ((TemplateInstance *) dsym->parent)->toChars () : dsym->ident->toChars ();
2275 tree decl = build_decl (make_location_t (dsym->loc), TYPE_DECL,
2276 get_identifier (name), type);
2277 SET_DECL_ASSEMBLER_NAME (decl, get_identifier (d_mangle_decl (dsym)));
2278 TREE_PUBLIC (decl) = 1;
2279 DECL_CONTEXT (decl) = d_decl_context (dsym);
2281 TYPE_CONTEXT (type) = DECL_CONTEXT (decl);
2282 TYPE_NAME (type) = decl;
2284 /* Not sure if there is a need for separate TYPE_DECLs in
2285 TYPE_NAME and TYPE_STUB_DECL. */
2286 if (TREE_CODE (type) == ENUMERAL_TYPE || RECORD_OR_UNION_TYPE_P (type))
2288 DECL_ARTIFICIAL (decl) = 1;
2289 TYPE_STUB_DECL (type) = decl;
2291 else if (type != TYPE_MAIN_VARIANT (type))
2292 DECL_ORIGINAL_TYPE (decl) = TYPE_MAIN_VARIANT (type);
2294 rest_of_decl_compilation (decl, DECL_FILE_SCOPE_P (decl), 0);
2297 /* Create a declaration for field NAME of a given TYPE, setting the flags
2298 for whether the field is ARTIFICIAL and/or IGNORED. */
2300 tree
2301 create_field_decl (tree type, const char *name, int artificial, int ignored)
2303 tree decl = build_decl (input_location, FIELD_DECL,
2304 name ? get_identifier (name) : NULL_TREE, type);
2305 DECL_ARTIFICIAL (decl) = artificial;
2306 DECL_IGNORED_P (decl) = ignored;
2308 return decl;
2311 /* Return the COMDAT group into which DECL should be placed. */
2313 static tree
2314 d_comdat_group (tree decl)
2316 /* If already part of a comdat group, use that. */
2317 if (DECL_COMDAT_GROUP (decl))
2318 return DECL_COMDAT_GROUP (decl);
2320 return DECL_ASSEMBLER_NAME (decl);
2323 /* Set DECL up to have the closest approximation of "initialized common"
2324 linkage available. */
2326 static void
2327 d_comdat_linkage (tree decl)
2329 /* COMDAT definitions have to be public. */
2330 gcc_assert (TREE_PUBLIC (decl));
2332 if (supports_one_only ())
2333 make_decl_one_only (decl, d_comdat_group (decl));
2334 else if ((TREE_CODE (decl) == FUNCTION_DECL && DECL_INSTANTIATED (decl))
2335 || (VAR_P (decl) && DECL_ARTIFICIAL (decl)))
2336 /* We can just emit function and compiler-generated variables statically;
2337 having multiple copies is (for the most part) only a waste of space. */
2338 TREE_PUBLIC (decl) = 0;
2339 else if (DECL_INITIAL (decl) == NULL_TREE
2340 || DECL_INITIAL (decl) == error_mark_node)
2341 /* Fallback, cannot have multiple copies. */
2342 DECL_COMMON (decl) = 1;
2344 if (TREE_PUBLIC (decl) && DECL_INSTANTIATED (decl))
2345 DECL_COMDAT (decl) = 1;
2348 /* Set DECL up to have the closest approximation of "weak" linkage. */
2350 static void
2351 d_weak_linkage (tree decl)
2353 /* Weak definitions have to be public. */
2354 gcc_assert (TREE_PUBLIC (decl));
2356 /* Allow comdat linkage to be forced with the flag `-fno-weak-templates'. */
2357 if (!flag_weak_templates || !TARGET_SUPPORTS_WEAK)
2358 return d_comdat_linkage (decl);
2360 declare_weak (decl);
2363 /* DECL is a FUNCTION_DECL or a VAR_DECL with static storage. Set flags to
2364 reflect the linkage that DECL will receive in the object file. */
2366 void
2367 set_linkage_for_decl (tree decl)
2369 gcc_assert (VAR_OR_FUNCTION_DECL_P (decl) && TREE_STATIC (decl));
2371 /* Non-public decls keep their internal linkage. */
2372 if (!TREE_PUBLIC (decl))
2373 return;
2375 /* Don't need to give private or protected symbols a special linkage. */
2376 if ((TREE_PRIVATE (decl) || TREE_PROTECTED (decl))
2377 && !DECL_INSTANTIATED (decl))
2378 return;
2380 /* Functions declared as `pragma(inline, true)' can appear in multiple
2381 translation units. */
2382 if (TREE_CODE (decl) == FUNCTION_DECL && DECL_DECLARED_INLINE_P (decl))
2383 return d_comdat_linkage (decl);
2385 /* If all instantiations must go in COMDAT, give them that linkage.
2386 This also applies to other extern declarations, so that it is possible
2387 for them to override template declarations. */
2388 if (targetdm.d_templates_always_comdat)
2390 /* Make sure that instantiations are not removed. */
2391 if (flag_weak_templates && DECL_INSTANTIATED (decl))
2392 d_mark_needed (decl);
2394 return d_comdat_linkage (decl);
2397 /* Instantiated variables and functions need to be overridable by any other
2398 symbol with the same name, so give them weak linkage. */
2399 if (DECL_INSTANTIATED (decl))
2400 return d_weak_linkage (decl);
2402 /* Compiler generated public symbols can appear in multiple contexts. */
2403 if (DECL_ARTIFICIAL (decl))
2404 return d_weak_linkage (decl);