d: Merge upstream dmd 6d5bffa54
[gcc.git] / gcc / d / decl.cc
1 /* decl.cc -- Lower D frontend declarations to GCC trees.
2 Copyright (C) 2006-2020 Free Software Foundation, Inc.
3
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.
8
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.
13
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/>. */
17
18 #include "config.h"
19 #include "system.h"
20 #include "coretypes.h"
21
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"
39
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
57 #include "d-tree.h"
58
59
60 /* Return identifier for the external mangled name of DECL. */
61
62 const char *
63 d_mangle_decl (Dsymbol *decl)
64 {
65 if (decl->isFuncDeclaration ())
66 return mangleExact ((FuncDeclaration *)decl);
67 else
68 {
69 OutBuffer buf;
70 mangleToBuffer (decl, &buf);
71 return buf.extractString ();
72 }
73 }
74
75 /* Generate a mangled identifier using NAME and SUFFIX, prefixed by the
76 assembler name for DECL. */
77
78 tree
79 mangle_internal_decl (Dsymbol *decl, const char *name, const char *suffix)
80 {
81 const char *prefix = d_mangle_decl (decl);
82 unsigned namelen = strlen (name);
83 unsigned buflen = (2 + strlen (prefix) + namelen + strlen (suffix)) * 2;
84 char *buf = (char *) alloca (buflen);
85
86 snprintf (buf, buflen, "_D%s%u%s%s", prefix, namelen, name, suffix);
87 tree ident = get_identifier (buf);
88
89 /* Symbol is not found in user code, but generate a readable name for it
90 anyway for debug and diagnostic reporting. */
91 snprintf (buf, buflen, "%s.%s", decl->toPrettyChars (), name);
92 IDENTIFIER_PRETTY_NAME (ident) = get_identifier (buf);
93
94 return ident;
95 }
96
97 /* Returns true if DECL is from the gcc.attribute module. */
98
99 static bool
100 gcc_attribute_p (Dsymbol *decl)
101 {
102 ModuleDeclaration *md = decl->getModule ()->md;
103
104 if (md && md->packages && md->packages->length == 1)
105 {
106 if (!strcmp ((*md->packages)[0]->toChars (), "gcc")
107 && !strcmp (md->id->toChars (), "attribute"))
108 return true;
109 }
110
111 return false;
112 }
113
114 /* Implements the visitor interface to lower all Declaration AST classes
115 emitted from the D Front-end to GCC trees.
116 All visit methods accept one parameter D, which holds the frontend AST
117 of the declaration to compile. These also don't return any value, instead
118 generated code are appened to global_declarations or added to the
119 current_binding_level by d_pushdecl(). */
120
121 class DeclVisitor : public Visitor
122 {
123 using Visitor::visit;
124
125 /* If we're lowering the body of a version(unittest) condition. */
126 bool in_version_unittest_;
127
128 public:
129 DeclVisitor (void)
130 {
131 this->in_version_unittest_ = false;
132 }
133
134 /* Helper for generating code for the dsymbol AST class D.
135 Sets up the location of the symbol before lowering. */
136
137 void build_dsymbol (Dsymbol *d)
138 {
139 location_t saved_location = input_location;
140 input_location = make_location_t (d->loc);
141 d->accept (this);
142 input_location = saved_location;
143 }
144
145 /* This should be overridden by each declaration class. */
146
147 void visit (Dsymbol *)
148 {
149 }
150
151 /* Compile a D module, and all members of it. */
152
153 void visit (Module *d)
154 {
155 if (d->semanticRun >= PASSobj)
156 return;
157
158 build_module_tree (d);
159 d->semanticRun = PASSobj;
160 }
161
162 /* Write the imported symbol to debug. */
163
164 void visit (Import *d)
165 {
166 if (d->semanticRun >= PASSobj)
167 return;
168
169 /* Implements import declarations by telling the debug back-end we are
170 importing the NAMESPACE_DECL of the module or IMPORTED_DECL of the
171 declaration into the current lexical scope CONTEXT. NAME is set if
172 this is a renamed import. */
173 if (d->isstatic)
174 return;
175
176 /* Get the context of this import, this should never be null. */
177 tree context = d_module_context ();
178
179 if (d->ident == NULL)
180 {
181 /* Importing declaration list. */
182 for (size_t i = 0; i < d->names.length; i++)
183 {
184 AliasDeclaration *aliasdecl = d->aliasdecls[i];
185 tree decl = build_import_decl (aliasdecl);
186
187 /* Skip over unhandled imports. */
188 if (decl == NULL_TREE)
189 continue;
190
191 Identifier *alias = d->aliases[i];
192 tree name = (alias != NULL)
193 ? get_identifier (alias->toChars ()) : NULL_TREE;
194
195 debug_hooks->imported_module_or_decl (decl, name, context,
196 false, false);
197 }
198 }
199 else
200 {
201 /* Importing the entire module. */
202 tree decl = build_import_decl (d->mod);
203
204 tree name = (d->aliasId != NULL)
205 ? get_identifier (d->aliasId->toChars ()) : NULL_TREE;
206
207 debug_hooks->imported_module_or_decl (decl, name, context,
208 false, false);
209 }
210
211 d->semanticRun = PASSobj;
212 }
213
214 /* Expand any local variables found in tuples. */
215
216 void visit (TupleDeclaration *d)
217 {
218 for (size_t i = 0; i < d->objects->length; i++)
219 {
220 RootObject *o = (*d->objects)[i];
221 if ((o->dyncast () == DYNCAST_EXPRESSION)
222 && ((Expression *) o)->op == TOKdsymbol)
223 {
224 Declaration *d = ((DsymbolExp *) o)->s->isDeclaration ();
225 if (d)
226 this->build_dsymbol (d);
227 }
228 }
229 }
230
231 /* Walk over all declarations in the attribute scope. */
232
233 void visit (AttribDeclaration *d)
234 {
235 Dsymbols *ds = d->include (NULL);
236
237 if (!ds)
238 return;
239
240 for (size_t i = 0; i < ds->length; i++)
241 this->build_dsymbol ((*ds)[i]);
242 }
243
244 /* Pragmas are a way to pass special information to the compiler and to add
245 vendor specific extensions to D. We don't do anything here, yet. */
246
247 void visit (PragmaDeclaration *d)
248 {
249 if (!global.params.ignoreUnsupportedPragmas)
250 {
251 if (d->ident == Identifier::idPool ("lib")
252 || d->ident == Identifier::idPool ("startaddress"))
253 {
254 warning_at (make_location_t (d->loc), OPT_Wunknown_pragmas,
255 "pragma(%s) not implemented", d->ident->toChars ());
256 }
257 }
258
259 visit ((AttribDeclaration *) d);
260 }
261
262 /* Conditional compilation is the process of selecting which code to compile
263 and which code to not compile. Look for version conditions that may */
264
265 void visit (ConditionalDeclaration *d)
266 {
267 bool old_condition = this->in_version_unittest_;
268
269 if (global.params.useUnitTests)
270 {
271 VersionCondition *vc = d->condition->isVersionCondition ();
272 if (vc && vc->ident == Identifier::idPool ("unittest"))
273 this->in_version_unittest_ = true;
274 }
275
276 visit ((AttribDeclaration *) d);
277
278 this->in_version_unittest_ = old_condition;
279 }
280
281 /* Walk over all members in the namespace scope. */
282
283 void visit (Nspace *d)
284 {
285 if (isError (d) || !d->members)
286 return;
287
288 for (size_t i = 0; i < d->members->length; i++)
289 this->build_dsymbol ((*d->members)[i]);
290 }
291
292 /* Templates are D's approach to generic programming. They have no members
293 that can be emitted, however if the template is nested and used as a
294 voldemort type, then it's members must be compiled before the parent
295 function finishes. */
296
297 void visit (TemplateDeclaration *d)
298 {
299 /* Type cannot be directly named outside of the scope it's declared in, so
300 the only way it can be escaped is if the function has auto return. */
301 FuncDeclaration *fd = d_function_chain ? d_function_chain->function : NULL;
302
303 if (!fd || !fd->isAuto ())
304 return;
305
306 /* Check if the function returns an instantiated type that may contain
307 nested members. Only applies to classes or structs. */
308 Type *tb = fd->type->nextOf ()->baseElemOf ();
309
310 while (tb->ty == Tarray || tb->ty == Tpointer)
311 tb = tb->nextOf ()->baseElemOf ();
312
313 TemplateInstance *ti = NULL;
314
315 if (tb->ty == Tstruct)
316 ti = ((TypeStruct *) tb)->sym->isInstantiated ();
317 else if (tb->ty == Tclass)
318 ti = ((TypeClass *) tb)->sym->isInstantiated ();
319
320 /* Return type is instantiated from this template declaration, walk over
321 all members of the instance. */
322 if (ti && ti->tempdecl == d)
323 this->build_dsymbol (ti);
324 }
325
326 /* Walk over all members in the instantiated template. */
327
328 void visit (TemplateInstance *d)
329 {
330 if (isError (d)|| !d->members)
331 return;
332
333 if (!d->needsCodegen ())
334 return;
335
336 for (size_t i = 0; i < d->members->length; i++)
337 this->build_dsymbol ((*d->members)[i]);
338 }
339
340 /* Walk over all members in the mixin template scope. */
341
342 void visit (TemplateMixin *d)
343 {
344 if (isError (d)|| !d->members)
345 return;
346
347 for (size_t i = 0; i < d->members->length; i++)
348 this->build_dsymbol ((*d->members)[i]);
349 }
350
351 /* Write out compiler generated TypeInfo, initializer and functions for the
352 given struct declaration, walking over all static members. */
353
354 void visit (StructDeclaration *d)
355 {
356 if (d->semanticRun >= PASSobj)
357 return;
358
359 if (d->type->ty == Terror)
360 {
361 error_at (make_location_t (d->loc),
362 "had semantic errors when compiling");
363 return;
364 }
365
366 /* Add this decl to the current binding level. */
367 tree ctype = build_ctype (d->type);
368 if (TYPE_NAME (ctype))
369 d_pushdecl (TYPE_NAME (ctype));
370
371 /* Anonymous structs/unions only exist as part of others,
372 do not output forward referenced structs. */
373 if (d->isAnonymous () || !d->members)
374 return;
375
376 /* Don't emit any symbols from gcc.attribute module. */
377 if (gcc_attribute_p (d))
378 return;
379
380 /* Generate TypeInfo. */
381 if (have_typeinfo_p (Type::dtypeinfo))
382 create_typeinfo (d->type, NULL);
383
384 /* Generate static initializer. */
385 d->sinit = aggregate_initializer_decl (d);
386 DECL_INITIAL (d->sinit) = layout_struct_initializer (d);
387
388 if (d->isInstantiated ())
389 d_linkonce_linkage (d->sinit);
390
391 d_finish_decl (d->sinit);
392
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]);
397
398 /* Put out xopEquals, xopCmp and xopHash. */
399 if (d->xeq && d->xeq != d->xerreq)
400 this->build_dsymbol (d->xeq);
401
402 if (d->xcmp && d->xcmp != d->xerrcmp)
403 this->build_dsymbol (d->xcmp);
404
405 if (d->xhash)
406 this->build_dsymbol (d->xhash);
407
408 d->semanticRun = PASSobj;
409 }
410
411 /* Finish semantic analysis of functions in vtbl for class CD. */
412
413 bool finish_vtable (ClassDeclaration *d)
414 {
415 bool has_errors = false;
416
417 /* Finish semantic analysis of functions in vtbl[]. */
418 for (size_t i = d->vtblOffset (); i < d->vtbl.length; i++)
419 {
420 FuncDeclaration *fd = d->vtbl[i]->isFuncDeclaration ();
421
422 if (!fd || (!fd->fbody && d->isAbstract ()))
423 continue;
424
425 /* Ensure function has a return value. */
426 if (!fd->functionSemantic ())
427 has_errors = true;
428
429 /* No name hiding to check for. */
430 if (!d->isFuncHidden (fd) || fd->isFuture ())
431 continue;
432
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++)
437 {
438 if (j == i)
439 continue;
440
441 FuncDeclaration *fd2 = d->vtbl[j]->isFuncDeclaration ();
442 if (!fd2->ident->equals (fd->ident))
443 continue;
444
445 /* The function is marked as @__future, a deprecation has
446 already been given by the frontend. */
447 if (fd2->isFuture ())
448 continue;
449
450 if (fd->leastAsSpecialized (fd2) || fd2->leastAsSpecialized (fd))
451 {
452 TypeFunction *tf = (TypeFunction *) fd->type;
453 if (tf->ty == Tfunction)
454 {
455 error_at (make_location_t (fd->loc), "use of %qs",
456 fd->toPrettyChars ());
457 inform (make_location_t (fd2->loc), "is hidden by %qs",
458 fd2->toPrettyChars ());
459 inform (make_location_t (d->loc),
460 "use %<alias %s = %s.%s;%> to introduce base class "
461 "overload set", fd->toChars (),
462 fd->parent->toChars (), fd->toChars ());
463 }
464 else
465 {
466 error_at (make_location_t (fd->loc), "use of %qs",
467 fd->toPrettyChars ());
468 inform (make_location_t (fd2->loc), "is hidden by %qs",
469 fd2->toPrettyChars ());
470 }
471
472 has_errors = true;
473 break;
474 }
475 }
476 }
477
478 return !has_errors;
479 }
480
481 /* Write out compiler generated TypeInfo, initializer and vtables for the
482 given class declaration, walking over all static members. */
483
484 void visit (ClassDeclaration *d)
485 {
486 if (d->semanticRun >= PASSobj)
487 return;
488
489 if (d->type->ty == Terror)
490 {
491 error_at (make_location_t (d->loc),
492 "had semantic errors when compiling");
493 return;
494 }
495
496 if (!d->members)
497 return;
498
499 /* Put out the members. */
500 for (size_t i = 0; i < d->members->length; i++)
501 this->build_dsymbol ((*d->members)[i]);
502
503 /* If something goes wrong during final semantic pass, don't bother with
504 the rest as we may have incomplete info. */
505 if (!this->finish_vtable (d))
506 return;
507
508 /* Generate C symbols. */
509 d->csym = get_classinfo_decl (d);
510 d->vtblsym = get_vtable_decl (d);
511 d->sinit = aggregate_initializer_decl (d);
512
513 /* Generate static initializer. */
514 DECL_INITIAL (d->sinit) = layout_class_initializer (d);
515 d_linkonce_linkage (d->sinit);
516 d_finish_decl (d->sinit);
517
518 /* Put out the TypeInfo. */
519 if (have_typeinfo_p (Type::dtypeinfo))
520 create_typeinfo (d->type, NULL);
521
522 DECL_INITIAL (d->csym) = layout_classinfo (d);
523 d_linkonce_linkage (d->csym);
524 d_finish_decl (d->csym);
525
526 /* Put out the vtbl[]. */
527 vec<constructor_elt, va_gc> *elms = NULL;
528
529 /* First entry is ClassInfo reference. */
530 if (d->vtblOffset ())
531 CONSTRUCTOR_APPEND_ELT (elms, size_zero_node, build_address (d->csym));
532
533 for (size_t i = d->vtblOffset (); i < d->vtbl.length; i++)
534 {
535 FuncDeclaration *fd = d->vtbl[i]->isFuncDeclaration ();
536
537 if (fd && (fd->fbody || !d->isAbstract()))
538 {
539 CONSTRUCTOR_APPEND_ELT (elms, size_int (i),
540 build_address (get_symbol_decl (fd)));
541 }
542 }
543
544 DECL_INITIAL (d->vtblsym)
545 = build_constructor (TREE_TYPE (d->vtblsym), elms);
546 d_comdat_linkage (d->vtblsym);
547 d_finish_decl (d->vtblsym);
548
549 /* Add this decl to the current binding level. */
550 tree ctype = TREE_TYPE (build_ctype (d->type));
551 if (TYPE_NAME (ctype))
552 d_pushdecl (TYPE_NAME (ctype));
553
554 d->semanticRun = PASSobj;
555 }
556
557 /* Write out compiler generated TypeInfo and vtables for the given interface
558 declaration, walking over all static members. */
559
560 void visit (InterfaceDeclaration *d)
561 {
562 if (d->semanticRun >= PASSobj)
563 return;
564
565 if (d->type->ty == Terror)
566 {
567 error_at (make_location_t (d->loc),
568 "had semantic errors when compiling");
569 return;
570 }
571
572 if (!d->members)
573 return;
574
575 /* Put out the members. */
576 for (size_t i = 0; i < d->members->length; i++)
577 this->build_dsymbol ((*d->members)[i]);
578
579 /* Generate C symbols. */
580 d->csym = get_classinfo_decl (d);
581
582 /* Put out the TypeInfo. */
583 if (have_typeinfo_p (Type::dtypeinfo))
584 {
585 create_typeinfo (d->type, NULL);
586 this->build_dsymbol (d->type->vtinfo);
587 }
588
589 DECL_INITIAL (d->csym) = layout_classinfo (d);
590 d_linkonce_linkage (d->csym);
591 d_finish_decl (d->csym);
592
593 /* Add this decl to the current binding level. */
594 tree ctype = TREE_TYPE (build_ctype (d->type));
595 if (TYPE_NAME (ctype))
596 d_pushdecl (TYPE_NAME (ctype));
597
598 d->semanticRun = PASSobj;
599 }
600
601 /* Write out compiler generated TypeInfo and initializer for the given
602 enum declaration. */
603
604 void visit (EnumDeclaration *d)
605 {
606 if (d->semanticRun >= PASSobj)
607 return;
608
609 if (d->errors || d->type->ty == Terror)
610 {
611 error_at (make_location_t (d->loc),
612 "had semantic errors when compiling");
613 return;
614 }
615
616 if (d->isAnonymous ())
617 return;
618
619 /* Generate TypeInfo. */
620 if (have_typeinfo_p (Type::dtypeinfo))
621 create_typeinfo (d->type, NULL);
622
623 TypeEnum *tc = (TypeEnum *) d->type;
624 if (tc->sym->members && !d->type->isZeroInit ())
625 {
626 /* Generate static initializer. */
627 d->sinit = enum_initializer_decl (d);
628 DECL_INITIAL (d->sinit) = build_expr (tc->sym->defaultval, true);
629
630 if (d->isInstantiated ())
631 d_linkonce_linkage (d->sinit);
632
633 d_finish_decl (d->sinit);
634
635 /* Add this decl to the current binding level. */
636 tree ctype = build_ctype (d->type);
637 if (TREE_CODE (ctype) == ENUMERAL_TYPE && TYPE_NAME (ctype))
638 d_pushdecl (TYPE_NAME (ctype));
639 }
640
641 d->semanticRun = PASSobj;
642 }
643
644 /* Finish up a variable declaration and push it into the current scope.
645 This can either be a static, local or manifest constant. */
646
647 void visit (VarDeclaration *d)
648 {
649 if (d->semanticRun >= PASSobj)
650 return;
651
652 if (d->type->ty == Terror)
653 {
654 error_at (make_location_t (d->loc),
655 "had semantic errors when compiling");
656 return;
657 }
658
659 if (d->aliassym)
660 {
661 this->build_dsymbol (d->toAlias ());
662 return;
663 }
664
665 /* Do not store variables we cannot take the address of,
666 but keep the values for purposes of debugging. */
667 if (!d->canTakeAddressOf ())
668 {
669 /* Don't know if there is a good way to handle instantiations. */
670 if (d->isInstantiated ())
671 return;
672
673 /* Cannot make an expression out of a void initializer. */
674 if (!d->_init || d->_init->isVoidInitializer ())
675 return;
676
677 tree decl = get_symbol_decl (d);
678 Expression *ie = initializerToExpression (d->_init);
679
680 /* CONST_DECL was initially intended for enumerals and may be used for
681 scalars in general, but not for aggregates. Here a non-constant
682 value is generated anyway so as the CONST_DECL only serves as a
683 placeholder for the value, however the DECL itself should never be
684 referenced in any generated code, or passed to the back-end. */
685 if (!d->type->isscalar ())
686 DECL_INITIAL (decl) = build_expr (ie, false);
687 else
688 {
689 DECL_INITIAL (decl) = build_expr (ie, true);
690 d_pushdecl (decl);
691 rest_of_decl_compilation (decl, 1, 0);
692 }
693 }
694 else if (d->isDataseg () && !(d->storage_class & STCextern))
695 {
696 tree decl = get_symbol_decl (d);
697
698 /* Duplicated VarDeclarations map to the same symbol. Check if this
699 is the one declaration which will be emitted. */
700 tree ident = DECL_ASSEMBLER_NAME (decl);
701 if (IDENTIFIER_DSYMBOL (ident) && IDENTIFIER_DSYMBOL (ident) != d)
702 return;
703
704 /* How big a symbol can be should depend on back-end. */
705 tree size = build_integer_cst (d->type->size (d->loc),
706 build_ctype (Type::tsize_t));
707 if (!valid_constant_size_p (size))
708 {
709 error_at (make_location_t (d->loc), "size is too large");
710 return;
711 }
712
713 if (d->_init && !d->_init->isVoidInitializer ())
714 {
715 Expression *e = initializerToExpression (d->_init, d->type);
716 DECL_INITIAL (decl) = build_expr (e, true);
717 }
718 else
719 {
720 if (d->type->ty == Tstruct)
721 {
722 StructDeclaration *sd = ((TypeStruct *) d->type)->sym;
723 DECL_INITIAL (decl) = layout_struct_initializer (sd);
724 }
725 else
726 {
727 Expression *e = d->type->defaultInitLiteral (d->loc);
728 DECL_INITIAL (decl) = build_expr (e, true);
729 }
730 }
731
732 /* Frontend should have already caught this. */
733 gcc_assert (!integer_zerop (size)
734 || d->type->toBasetype ()->ty == Tsarray);
735
736 d_finish_decl (decl);
737
738 /* Maybe record the var against the current module. */
739 register_module_decl (d);
740 }
741 else if (!d->isDataseg () && !d->isMember ())
742 {
743 /* This is needed for VarDeclarations in mixins that are to be local
744 variables of a function. Otherwise, it would be enough to make
745 a check for isVarDeclaration() in DeclarationExp codegen. */
746 declare_local_var (d);
747
748 if (d->_init)
749 {
750 tree decl = get_symbol_decl (d);
751
752 if (!d->_init->isVoidInitializer ())
753 {
754 ExpInitializer *vinit = d->_init->isExpInitializer ();
755 Expression *ie = initializerToExpression (vinit);
756 tree exp = build_expr (ie);
757
758 /* Maybe put variable on list of things needing destruction. */
759 if (d->needsScopeDtor ())
760 {
761 vec_safe_push (d_function_chain->vars_in_scope, decl);
762 /* Force a TARGET_EXPR to add the corresponding cleanup. */
763 exp = force_target_expr (compound_expr (exp, decl));
764 TARGET_EXPR_CLEANUP (exp) = build_expr (d->edtor);
765 }
766
767 add_stmt (exp);
768 }
769 else if (d->size (d->loc) != 0)
770 {
771 /* Zero-length arrays do not have an initializer. */
772 warning (OPT_Wuninitialized, "uninitialized variable '%s'",
773 d->ident ? d->ident->toChars () : "(no name)");
774 }
775 }
776 }
777
778 d->semanticRun = PASSobj;
779 }
780
781 /* Generate and compile a static TypeInfo declaration, but only if it is
782 needed in the current compilation. */
783
784 void visit (TypeInfoDeclaration *d)
785 {
786 if (d->semanticRun >= PASSobj)
787 return;
788
789 if (speculative_type_p (d->tinfo))
790 return;
791
792 tree t = get_typeinfo_decl (d);
793 DECL_INITIAL (t) = layout_typeinfo (d);
794 d_finish_decl (t);
795 d->semanticRun = PASSobj;
796 }
797
798 /* Finish up a function declaration and compile it all the way
799 down to assembler language output. */
800
801 void visit (FuncDeclaration *d)
802 {
803 /* Already generated the function. */
804 if (d->semanticRun >= PASSobj)
805 return;
806
807 /* Don't emit any symbols from gcc.attribute module. */
808 if (gcc_attribute_p (d))
809 return;
810
811 /* Not emitting unittest functions. */
812 if (!global.params.useUnitTests && d->isUnitTestDeclaration ())
813 return;
814
815 /* Check if any errors occurred when running semantic. */
816 if (d->type->ty == Tfunction)
817 {
818 TypeFunction *tf = (TypeFunction *) d->type;
819 if (tf->next == NULL || tf->next->ty == Terror)
820 return;
821 }
822
823 if (d->semantic3Errors)
824 return;
825
826 if (d->isNested ())
827 {
828 FuncDeclaration *fdp = d;
829 while (fdp && fdp->isNested ())
830 {
831 fdp = fdp->toParent2 ()->isFuncDeclaration ();
832
833 if (fdp == NULL)
834 break;
835
836 /* Parent failed to compile, but errors were gagged. */
837 if (fdp->semantic3Errors)
838 return;
839 }
840 }
841
842 /* Ensure all semantic passes have run. */
843 if (d->semanticRun < PASSsemantic3)
844 {
845 d->functionSemantic3 ();
846 Module::runDeferredSemantic3 ();
847 }
848
849 if (global.errors)
850 return;
851
852 /* Duplicated FuncDeclarations map to the same symbol. Check if this
853 is the one declaration which will be emitted. */
854 tree fndecl = get_symbol_decl (d);
855 tree ident = DECL_ASSEMBLER_NAME (fndecl);
856 if (IDENTIFIER_DSYMBOL (ident) && IDENTIFIER_DSYMBOL (ident) != d)
857 return;
858
859 if (!d->fbody)
860 {
861 rest_of_decl_compilation (fndecl, 1, 0);
862 return;
863 }
864
865 if (global.params.verbose)
866 message ("function %s", d->toPrettyChars ());
867
868 /* Start generating code for this function. */
869 gcc_assert (d->semanticRun == PASSsemantic3done);
870 d->semanticRun = PASSobj;
871
872 tree old_context = start_function (d);
873
874 tree parm_decl = NULL_TREE;
875 tree param_list = NULL_TREE;
876
877 /* Special arguments... */
878
879 /* 'this' parameter:
880 For nested functions, D still generates a vthis, but it
881 should not be referenced in any expression. */
882 if (d->vthis)
883 {
884 parm_decl = get_symbol_decl (d->vthis);
885 DECL_ARTIFICIAL (parm_decl) = 1;
886 TREE_READONLY (parm_decl) = 1;
887
888 if (d->vthis->type == Type::tvoidptr)
889 {
890 /* Replace generic pointer with back-end closure type
891 (this wins for gdb). */
892 tree frame_type = FRAMEINFO_TYPE (get_frameinfo (d));
893 gcc_assert (frame_type != NULL_TREE);
894 TREE_TYPE (parm_decl) = build_pointer_type (frame_type);
895 }
896
897 param_list = chainon (param_list, parm_decl);
898 d_function_chain->static_chain = parm_decl;
899 }
900
901 /* _arguments parameter. */
902 if (d->v_arguments)
903 {
904 parm_decl = get_symbol_decl (d->v_arguments);
905 param_list = chainon (param_list, parm_decl);
906 }
907
908 /* formal function parameters. */
909 size_t n_parameters = d->parameters ? d->parameters->length : 0;
910
911 for (size_t i = 0; i < n_parameters; i++)
912 {
913 VarDeclaration *param = (*d->parameters)[i];
914 parm_decl = get_symbol_decl (param);
915 /* Chain them in the correct order. */
916 param_list = chainon (param_list, parm_decl);
917 }
918
919 DECL_ARGUMENTS (fndecl) = param_list;
920 DECL_IN_UNITTEST_CONDITION_P (fndecl) = this->in_version_unittest_;
921 rest_of_decl_compilation (fndecl, 1, 0);
922
923 /* If this is a member function that nested (possibly indirectly) in another
924 function, construct an expession for this member function's static chain
925 by going through parent link of nested classes. */
926 if (d->isThis ())
927 {
928 AggregateDeclaration *ad = d->isThis ();
929 tree this_tree = get_symbol_decl (d->vthis);
930
931 while (ad->isNested ())
932 {
933 Dsymbol *pd = ad->toParent2 ();
934 tree vthis_field = get_symbol_decl (ad->vthis);
935 this_tree = component_ref (build_deref (this_tree), vthis_field);
936
937 ad = pd->isAggregateDeclaration ();
938 if (ad == NULL)
939 {
940 cfun->language->static_chain = this_tree;
941 break;
942 }
943 }
944 }
945
946 /* May change cfun->static_chain. */
947 build_closure (d);
948
949 if (d->vresult)
950 declare_local_var (d->vresult);
951
952 if (d->v_argptr)
953 push_stmt_list ();
954
955 /* Named return value optimisation support for D.
956 Implemented by overriding all the RETURN_EXPRs and replacing all
957 occurrences of VAR with the RESULT_DECL for the function.
958 This is only worth doing for functions that can return in memory. */
959 if (d->nrvo_can)
960 {
961 tree restype = TREE_TYPE (DECL_RESULT (fndecl));
962
963 if (!AGGREGATE_TYPE_P (restype))
964 d->nrvo_can = 0;
965 else
966 d->nrvo_can = aggregate_value_p (restype, fndecl);
967 }
968
969 if (d->nrvo_can)
970 {
971 tree resdecl = DECL_RESULT (fndecl);
972
973 TREE_TYPE (resdecl)
974 = build_reference_type (TREE_TYPE (resdecl));
975 DECL_BY_REFERENCE (resdecl) = 1;
976 TREE_ADDRESSABLE (resdecl) = 0;
977 relayout_decl (resdecl);
978
979 if (d->nrvo_var)
980 {
981 tree var = get_symbol_decl (d->nrvo_var);
982
983 /* Copy name from VAR to RESULT. */
984 DECL_NAME (resdecl) = DECL_NAME (var);
985 /* Don't forget that we take its address. */
986 TREE_ADDRESSABLE (var) = 1;
987 resdecl = build_deref (resdecl);
988
989 SET_DECL_VALUE_EXPR (var, resdecl);
990 DECL_HAS_VALUE_EXPR_P (var) = 1;
991 SET_DECL_LANG_NRVO (var, resdecl);
992 }
993 }
994
995 build_function_body (d);
996
997 /* Initialize the _argptr variable. */
998 if (d->v_argptr)
999 {
1000 tree body = pop_stmt_list ();
1001 tree var = get_decl_tree (d->v_argptr);
1002 var = build_address (var);
1003
1004 tree init = build_call_expr (builtin_decl_explicit (BUILT_IN_VA_START),
1005 2, var, parm_decl);
1006 declare_local_var (d->v_argptr);
1007 add_stmt (init);
1008
1009 tree cleanup = build_call_expr (builtin_decl_explicit (BUILT_IN_VA_END),
1010 1, var);
1011 add_stmt (build2 (TRY_FINALLY_EXPR, void_type_node, body, cleanup));
1012 }
1013
1014 finish_function (old_context);
1015
1016 /* Maybe record the function against the current module. */
1017 register_module_decl (d);
1018 }
1019 };
1020
1021 /* Main entry point for the DeclVisitor interface to send
1022 the Declaration AST class D to GCC back-end. */
1023
1024 void
1025 build_decl_tree (Dsymbol *d)
1026 {
1027 location_t saved_location = input_location;
1028
1029 /* Set input location, empty DECL_SOURCE_FILE can crash debug generator. */
1030 if (d->loc.filename)
1031 input_location = make_location_t (d->loc);
1032 else
1033 input_location = make_location_t (Loc ("<no_file>", 1, 0));
1034
1035 DeclVisitor v = DeclVisitor ();
1036 v.build_dsymbol (d);
1037
1038 input_location = saved_location;
1039 }
1040
1041 /* Return the decl for the symbol, create it if it doesn't already exist. */
1042
1043 tree
1044 get_symbol_decl (Declaration *decl)
1045 {
1046 if (decl->csym)
1047 return decl->csym;
1048
1049 /* Deal with placeholder symbols immediately:
1050 SymbolDeclaration is used as a shell around an initializer symbol. */
1051 SymbolDeclaration *sd = decl->isSymbolDeclaration ();
1052 if (sd)
1053 {
1054 decl->csym = aggregate_initializer_decl (sd->dsym);
1055 return decl->csym;
1056 }
1057
1058 /* Global static TypeInfo declaration. */
1059 if (decl->isTypeInfoDeclaration ())
1060 return get_typeinfo_decl ((TypeInfoDeclaration *) decl);
1061
1062 /* FuncAliasDeclaration is used to import functions from another scope. */
1063 FuncAliasDeclaration *fad = decl->isFuncAliasDeclaration ();
1064 if (fad)
1065 {
1066 decl->csym = get_symbol_decl (fad->funcalias);
1067 return decl->csym;
1068 }
1069
1070 /* It is possible for a field declaration symbol to be requested
1071 before the parent type has been built. */
1072 if (decl->isField ())
1073 {
1074 AggregateDeclaration *ad = decl->toParent ()->isAggregateDeclaration ();
1075 gcc_assert (ad != NULL);
1076
1077 /* Finishing off the type should create the associated FIELD_DECL. */
1078 build_ctype (ad->type);
1079 gcc_assert (decl->csym != NULL);
1080
1081 return decl->csym;
1082 }
1083
1084 /* Build the tree for the symbol. */
1085 FuncDeclaration *fd = decl->isFuncDeclaration ();
1086 if (fd)
1087 {
1088 /* Run full semantic on functions we need to know about. */
1089 if (!fd->functionSemantic ())
1090 {
1091 decl->csym = error_mark_node;
1092 return decl->csym;
1093 }
1094
1095 decl->csym = build_decl (make_location_t (decl->loc), FUNCTION_DECL,
1096 get_identifier (decl->ident->toChars ()),
1097 NULL_TREE);
1098
1099 /* Set function type afterwards as there could be self references. */
1100 TREE_TYPE (decl->csym) = build_ctype (fd->type);
1101
1102 /* Set DECL_INITIAL now if the function has a definition. */
1103 if (fd->fbody)
1104 DECL_INITIAL (decl->csym) = error_mark_node;
1105 else
1106 DECL_EXTERNAL (decl->csym) = 1;
1107 }
1108 else
1109 {
1110 /* Build the variable declaration. */
1111 VarDeclaration *vd = decl->isVarDeclaration ();
1112 gcc_assert (vd != NULL);
1113
1114 tree_code code = vd->isParameter () ? PARM_DECL
1115 : !vd->canTakeAddressOf () ? CONST_DECL
1116 : VAR_DECL;
1117 decl->csym = build_decl (make_location_t (decl->loc), code,
1118 get_identifier (decl->ident->toChars ()),
1119 declaration_type (vd));
1120
1121 /* If any alignment was set on the declaration. */
1122 if (vd->alignment != STRUCTALIGN_DEFAULT)
1123 {
1124 SET_DECL_ALIGN (decl->csym, vd->alignment * BITS_PER_UNIT);
1125 DECL_USER_ALIGN (decl->csym) = 1;
1126 }
1127
1128 if (vd->storage_class & STCextern)
1129 DECL_EXTERNAL (decl->csym) = 1;
1130 }
1131
1132 /* Set the declaration mangled identifier if static. */
1133 if (decl->isCodeseg () || decl->isDataseg ())
1134 {
1135 tree mangled_name;
1136
1137 if (decl->mangleOverride)
1138 mangled_name = get_identifier (decl->mangleOverride);
1139 else
1140 mangled_name = get_identifier (d_mangle_decl (decl));
1141
1142 mangled_name = targetm.mangle_decl_assembler_name (decl->csym,
1143 mangled_name);
1144 /* The frontend doesn't handle duplicate definitions of unused symbols
1145 with the same mangle. So a check is done here instead. */
1146 if (IDENTIFIER_DSYMBOL (mangled_name))
1147 {
1148 Declaration *other = IDENTIFIER_DSYMBOL (mangled_name);
1149 tree olddecl = decl->csym;
1150 decl->csym = get_symbol_decl (other);
1151
1152 /* The current declaration is a prototype or marked extern, merge
1153 applied user attributes and return. */
1154 if (DECL_EXTERNAL (olddecl) && !DECL_INITIAL (olddecl))
1155 {
1156 apply_user_attributes (decl, decl->csym);
1157 return decl->csym;
1158 }
1159 /* The previous declaration is a prototype or marked extern, set the
1160 current declaration as the main reference of the symbol. */
1161 else if (DECL_EXTERNAL (decl->csym) && !DECL_INITIAL (decl->csym))
1162 {
1163 IDENTIFIER_DSYMBOL (mangled_name) = decl;
1164 DECL_EXTERNAL (decl->csym) = 0;
1165 }
1166 /* Non-extern, non-templated decls shouldn't be defined twice. */
1167 else if (!decl->isInstantiated ())
1168 ScopeDsymbol::multiplyDefined (decl->loc, decl, other);
1169 }
1170 else
1171 {
1172 IDENTIFIER_PRETTY_NAME (mangled_name)
1173 = get_identifier (decl->toPrettyChars (true));
1174 IDENTIFIER_DSYMBOL (mangled_name) = decl;
1175
1176 SET_DECL_ASSEMBLER_NAME (decl->csym, mangled_name);
1177 }
1178 }
1179
1180 DECL_LANG_SPECIFIC (decl->csym) = build_lang_decl (decl);
1181 DECL_CONTEXT (decl->csym) = d_decl_context (decl);
1182
1183 if (TREE_CODE (decl->csym) == PARM_DECL)
1184 {
1185 /* Pass non-trivial structs by invisible reference. */
1186 if (TREE_ADDRESSABLE (TREE_TYPE (decl->csym)))
1187 {
1188 tree argtype = build_reference_type (TREE_TYPE (decl->csym));
1189 argtype = build_qualified_type (argtype, TYPE_QUAL_RESTRICT);
1190 gcc_assert (!DECL_BY_REFERENCE (decl->csym));
1191 TREE_TYPE (decl->csym) = argtype;
1192 DECL_BY_REFERENCE (decl->csym) = 1;
1193 TREE_ADDRESSABLE (decl->csym) = 0;
1194 relayout_decl (decl->csym);
1195 decl->storage_class |= STCref;
1196 }
1197
1198 DECL_ARG_TYPE (decl->csym) = TREE_TYPE (decl->csym);
1199 gcc_assert (TREE_CODE (DECL_CONTEXT (decl->csym)) == FUNCTION_DECL);
1200 }
1201 else if (TREE_CODE (decl->csym) == CONST_DECL)
1202 {
1203 /* Manifest constants have no address in memory. */
1204 TREE_CONSTANT (decl->csym) = 1;
1205 TREE_READONLY (decl->csym) = 1;
1206 }
1207 else if (TREE_CODE (decl->csym) == FUNCTION_DECL)
1208 {
1209 /* The real function type may differ from its declaration. */
1210 tree fntype = TREE_TYPE (decl->csym);
1211 tree newfntype = NULL_TREE;
1212
1213 if (fd->isNested ())
1214 {
1215 /* Add an extra argument for the frame/closure pointer, this is also
1216 required to be compatible with D delegates. */
1217 newfntype = build_vthis_function (void_type_node, fntype);
1218 }
1219 else if (fd->isThis ())
1220 {
1221 /* Add an extra argument for the 'this' parameter. The handle type is
1222 used even if there is no debug info. It is needed to make sure
1223 virtual member functions are not called statically. */
1224 AggregateDeclaration *ad = fd->isMember2 ();
1225 tree handle = build_ctype (ad->handleType ());
1226
1227 /* If handle is a pointer type, get record type. */
1228 if (!ad->isStructDeclaration ())
1229 handle = TREE_TYPE (handle);
1230
1231 newfntype = build_vthis_function (handle, fntype);
1232
1233 /* Set the vindex on virtual functions. */
1234 if (fd->isVirtual () && fd->vtblIndex != -1)
1235 {
1236 DECL_VINDEX (decl->csym) = size_int (fd->vtblIndex);
1237 DECL_VIRTUAL_P (decl->csym) = 1;
1238 }
1239 }
1240 else if (fd->isMain () || fd->isCMain ())
1241 {
1242 /* The main function is named 'D main' to distinguish from C main. */
1243 if (fd->isMain ())
1244 DECL_NAME (decl->csym) = get_identifier (fd->toPrettyChars (true));
1245
1246 /* 'void main' is implicitly converted to returning an int. */
1247 newfntype = build_function_type (d_int_type, TYPE_ARG_TYPES (fntype));
1248 }
1249
1250 if (newfntype != NULL_TREE)
1251 {
1252 /* Copy the old attributes from the original type. */
1253 TYPE_ATTRIBUTES (newfntype) = TYPE_ATTRIBUTES (fntype);
1254 TYPE_LANG_SPECIFIC (newfntype) = TYPE_LANG_SPECIFIC (fntype);
1255 TREE_ADDRESSABLE (newfntype) = TREE_ADDRESSABLE (fntype);
1256 TREE_TYPE (decl->csym) = newfntype;
1257 d_keep (newfntype);
1258 }
1259
1260 /* Miscellaneous function flags. */
1261 if (fd->isMember2 () || fd->isFuncLiteralDeclaration ())
1262 {
1263 /* See grokmethod in cp/decl.c. Maybe we shouldn't be setting inline
1264 flags without reason or proper handling. */
1265 DECL_DECLARED_INLINE_P (decl->csym) = 1;
1266 DECL_NO_INLINE_WARNING_P (decl->csym) = 1;
1267 }
1268
1269 /* In [pragma/inline], functions decorated with 'pragma(inline)' affects
1270 whether they are inlined or not. */
1271 if (fd->inlining == PINLINEalways)
1272 DECL_DECLARED_INLINE_P (decl->csym) = 1;
1273 else if (fd->inlining == PINLINEnever)
1274 DECL_UNINLINABLE (decl->csym) = 1;
1275
1276 /* Function was declared 'naked'. */
1277 if (fd->naked)
1278 {
1279 insert_decl_attribute (decl->csym, "naked");
1280 DECL_NO_INSTRUMENT_FUNCTION_ENTRY_EXIT (decl->csym) = 1;
1281 }
1282
1283 /* Vector array operations are always compiler generated. */
1284 if (fd->isArrayOp)
1285 {
1286 TREE_PUBLIC (decl->csym) = 1;
1287 DECL_ARTIFICIAL (decl->csym) = 1;
1288 DECL_DECLARED_INLINE_P (decl->csym) = 1;
1289 d_comdat_linkage (decl->csym);
1290 }
1291
1292 /* And so are ensure and require contracts. */
1293 if (fd->ident == Identifier::idPool ("ensure")
1294 || fd->ident == Identifier::idPool ("require"))
1295 {
1296 DECL_ARTIFICIAL (decl->csym) = 1;
1297 TREE_PUBLIC (decl->csym) = 1;
1298 }
1299
1300 if (decl->storage_class & STCfinal)
1301 DECL_FINAL_P (decl->csym) = 1;
1302
1303 /* Check whether this function is expanded by the frontend. */
1304 DECL_INTRINSIC_CODE (decl->csym) = INTRINSIC_NONE;
1305 maybe_set_intrinsic (fd);
1306
1307 /* For nested functions in particular, unnest fndecl in the cgraph, as
1308 all static chain passing is handled by the front-end. Do this even
1309 if we are not emitting the body. */
1310 struct cgraph_node *node = cgraph_node::get_create (decl->csym);
1311 if (node->origin)
1312 node->unnest ();
1313 }
1314
1315 /* Mark compiler generated temporaries as artificial. */
1316 if (decl->storage_class & STCtemp)
1317 DECL_ARTIFICIAL (decl->csym) = 1;
1318
1319 /* Propagate shared on the decl. */
1320 if (TYPE_SHARED (TREE_TYPE (decl->csym)))
1321 TREE_ADDRESSABLE (decl->csym) = 1;
1322
1323 /* Symbol was marked volatile. */
1324 if (decl->storage_class & STCvolatile)
1325 TREE_THIS_VOLATILE (decl->csym) = 1;
1326
1327 /* Protection attributes are used by the debugger. */
1328 if (decl->protection.kind == PROTprivate)
1329 TREE_PRIVATE (decl->csym) = 1;
1330 else if (decl->protection.kind == PROTprotected)
1331 TREE_PROTECTED (decl->csym) = 1;
1332
1333 /* Likewise, so could the deprecated attribute. */
1334 if (decl->storage_class & STCdeprecated)
1335 TREE_DEPRECATED (decl->csym) = 1;
1336
1337 #if TARGET_DLLIMPORT_DECL_ATTRIBUTES
1338 /* Have to test for import first. */
1339 if (decl->isImportedSymbol ())
1340 {
1341 insert_decl_attribute (decl->csym, "dllimport");
1342 DECL_DLLIMPORT_P (decl->csym) = 1;
1343 }
1344 else if (decl->isExport ())
1345 insert_decl_attribute (decl->csym, "dllexport");
1346 #endif
1347
1348 if (decl->isDataseg () || decl->isCodeseg () || decl->isThreadlocal ())
1349 {
1350 /* Set TREE_PUBLIC by default, but allow private template to override. */
1351 if (!fd || !fd->isNested ())
1352 TREE_PUBLIC (decl->csym) = 1;
1353
1354 TREE_STATIC (decl->csym) = 1;
1355 /* The decl has not been defined -- yet. */
1356 DECL_EXTERNAL (decl->csym) = 1;
1357
1358 if (decl->isInstantiated ())
1359 d_linkonce_linkage (decl->csym);
1360 }
1361
1362 /* Symbol is going in thread local storage. */
1363 if (decl->isThreadlocal () && !DECL_ARTIFICIAL (decl->csym))
1364 {
1365 if (global.params.vtls)
1366 message (decl->loc, "`%s` is thread local", decl->toChars ());
1367
1368 set_decl_tls_model (decl->csym, decl_default_tls_model (decl->csym));
1369 }
1370
1371 /* Apply any user attributes that may affect semantic meaning. */
1372 apply_user_attributes (decl, decl->csym);
1373
1374 /* %% Probably should be a little more intelligent about setting this. */
1375 TREE_USED (decl->csym) = 1;
1376 d_keep (decl->csym);
1377
1378 return decl->csym;
1379 }
1380
1381 /* Returns a declaration for a VAR_DECL. Used to create compiler-generated
1382 global variables. */
1383
1384 tree
1385 declare_extern_var (tree ident, tree type)
1386 {
1387 /* If the VAR_DECL has already been declared, return it. */
1388 if (IDENTIFIER_DECL_TREE (ident))
1389 return IDENTIFIER_DECL_TREE (ident);
1390
1391 tree name = IDENTIFIER_PRETTY_NAME (ident)
1392 ? IDENTIFIER_PRETTY_NAME (ident) : ident;
1393 tree decl = build_decl (input_location, VAR_DECL, name, type);
1394
1395 IDENTIFIER_DECL_TREE (ident) = decl;
1396 d_keep (decl);
1397
1398 SET_DECL_ASSEMBLER_NAME (decl, ident);
1399 DECL_ARTIFICIAL (decl) = 1;
1400 TREE_STATIC (decl) = 1;
1401 TREE_PUBLIC (decl) = 1;
1402
1403 /* The decl has not been defined -- yet. */
1404 DECL_EXTERNAL (decl) = 1;
1405
1406 return decl;
1407 }
1408
1409 /* Add local variable VAR into the current function body. */
1410
1411 void
1412 declare_local_var (VarDeclaration *var)
1413 {
1414 gcc_assert (!var->isDataseg () && !var->isMember ());
1415 gcc_assert (current_function_decl != NULL_TREE);
1416
1417 FuncDeclaration *fd = cfun->language->function;
1418 tree decl = get_symbol_decl (var);
1419
1420 gcc_assert (!TREE_STATIC (decl));
1421 d_pushdecl (decl);
1422 DECL_CONTEXT (decl) = current_function_decl;
1423
1424 /* Compiler generated symbols. */
1425 if (var == fd->vresult || var == fd->v_argptr)
1426 DECL_ARTIFICIAL (decl) = 1;
1427
1428 if (DECL_LANG_FRAME_FIELD (decl))
1429 {
1430 /* Fixes debugging local variables. */
1431 SET_DECL_VALUE_EXPR (decl, get_decl_tree (var));
1432 DECL_HAS_VALUE_EXPR_P (decl) = 1;
1433 }
1434 }
1435
1436 /* Return an unnamed local temporary of type TYPE. */
1437
1438 tree
1439 build_local_temp (tree type)
1440 {
1441 tree decl = build_decl (input_location, VAR_DECL, NULL_TREE, type);
1442
1443 DECL_CONTEXT (decl) = current_function_decl;
1444 DECL_ARTIFICIAL (decl) = 1;
1445 DECL_IGNORED_P (decl) = 1;
1446 d_pushdecl (decl);
1447
1448 return decl;
1449 }
1450
1451 /* Return the correct decl to be used for DECL. For VAR_DECLs, this could
1452 instead be a FIELD_DECL from a closure, or a RESULT_DECL from a named return
1453 value. For PARM_DECLs, this could be a FIELD_DECL for a non-local `this'.
1454 For all other kinds of decls, this just returns the result of
1455 get_symbol_decl(). */
1456
1457 tree
1458 get_decl_tree (Declaration *decl)
1459 {
1460 tree t = get_symbol_decl (decl);
1461 FuncDeclaration *fd = cfun ? cfun->language->function : NULL;
1462 VarDeclaration *vd = decl->isVarDeclaration ();
1463
1464 /* If cfun is NULL, then this is a global static. */
1465 if (vd == NULL || fd == NULL)
1466 return t;
1467
1468 /* Get the named return value. */
1469 if (DECL_LANG_NRVO (t))
1470 return DECL_LANG_NRVO (t);
1471
1472 /* Get the closure holding the var decl. */
1473 if (DECL_LANG_FRAME_FIELD (t))
1474 {
1475 FuncDeclaration *parent = vd->toParent2 ()->isFuncDeclaration ();
1476 tree frame_ref = get_framedecl (fd, parent);
1477
1478 return component_ref (build_deref (frame_ref),
1479 DECL_LANG_FRAME_FIELD (t));
1480 }
1481
1482 /* Get the non-local 'this' value by going through parent link
1483 of nested classes, this routine pretty much undoes what
1484 getRightThis in the frontend removes from codegen. */
1485 if (vd->parent != fd && vd->isThisDeclaration ())
1486 {
1487 /* Find the first parent that is a member function. */
1488 while (!fd->isMember2 ())
1489 {
1490 gcc_assert (fd->vthis);
1491 fd = fd->toParent2 ()->isFuncDeclaration ();
1492 gcc_assert (fd != NULL);
1493 }
1494
1495 AggregateDeclaration *ad = fd->isThis ();
1496 gcc_assert (ad != NULL);
1497
1498 t = get_decl_tree (fd->vthis);
1499 Dsymbol *outer = fd;
1500
1501 while (outer != vd->parent)
1502 {
1503 gcc_assert (ad != NULL);
1504 outer = ad->toParent2 ();
1505
1506 /* Get the this->this parent link. */
1507 tree vfield = get_symbol_decl (ad->vthis);
1508 t = component_ref (build_deref (t), vfield);
1509
1510 ad = outer->isAggregateDeclaration ();
1511 if (ad != NULL)
1512 continue;
1513
1514 fd = outer->isFuncDeclaration ();
1515 while (fd != NULL)
1516 {
1517 /* If outer function creates a closure, then the 'this'
1518 value would be the closure pointer, and the real
1519 'this' the first field of that closure. */
1520 tree ff = get_frameinfo (fd);
1521 if (FRAMEINFO_CREATES_FRAME (ff))
1522 {
1523 t = build_nop (build_pointer_type (FRAMEINFO_TYPE (ff)), t);
1524 t = indirect_ref (build_ctype (fd->vthis->type), t);
1525 }
1526
1527 if (fd == vd->parent)
1528 break;
1529
1530 /* Continue looking for the right `this'. */
1531 outer = outer->toParent2 ();
1532 fd = outer->isFuncDeclaration ();
1533 }
1534
1535 ad = outer->isAggregateDeclaration ();
1536 }
1537
1538 return t;
1539 }
1540
1541 /* Auto variable that the back end will handle for us. */
1542 return t;
1543 }
1544
1545 /* Finish up a variable declaration and compile it all the way to
1546 the assembler language output. */
1547
1548 void
1549 d_finish_decl (tree decl)
1550 {
1551 gcc_assert (!error_operand_p (decl));
1552
1553 /* We are sending this symbol to object file, can't be extern. */
1554 TREE_STATIC (decl) = 1;
1555 DECL_EXTERNAL (decl) = 0;
1556
1557 /* Update the TLS model as the linkage has been modified. */
1558 if (DECL_THREAD_LOCAL_P (decl))
1559 set_decl_tls_model (decl, decl_default_tls_model (decl));
1560
1561 relayout_decl (decl);
1562
1563 if (flag_checking && DECL_INITIAL (decl))
1564 {
1565 /* Initializer must never be bigger than symbol size. */
1566 dinteger_t tsize = int_size_in_bytes (TREE_TYPE (decl));
1567 dinteger_t dtsize = int_size_in_bytes (TREE_TYPE (DECL_INITIAL (decl)));
1568
1569 if (tsize < dtsize)
1570 {
1571 tree name = DECL_ASSEMBLER_NAME (decl);
1572
1573 internal_error ("Mismatch between declaration %qE size (%wd) and "
1574 "its initializer size (%wd).",
1575 IDENTIFIER_PRETTY_NAME (name)
1576 ? IDENTIFIER_PRETTY_NAME (name) : name,
1577 tsize, dtsize);
1578 }
1579 }
1580
1581 /* Without weak symbols, symbol should be put in .common, but that can't
1582 be done if there is a nonzero initializer. */
1583 if (DECL_COMDAT (decl) && DECL_COMMON (decl)
1584 && initializer_zerop (DECL_INITIAL (decl)))
1585 DECL_INITIAL (decl) = error_mark_node;
1586
1587 /* Add this decl to the current binding level. */
1588 d_pushdecl (decl);
1589
1590 rest_of_decl_compilation (decl, 1, 0);
1591 }
1592
1593 /* Thunk code is based on g++. */
1594
1595 static int thunk_labelno;
1596
1597 /* Create a static alias to function. */
1598
1599 static tree
1600 make_alias_for_thunk (tree function)
1601 {
1602 tree alias;
1603 char buf[256];
1604
1605 /* Thunks may reference extern functions which cannot be aliased. */
1606 if (DECL_EXTERNAL (function))
1607 return function;
1608
1609 targetm.asm_out.generate_internal_label (buf, "LTHUNK", thunk_labelno);
1610 thunk_labelno++;
1611
1612 alias = build_decl (DECL_SOURCE_LOCATION (function), FUNCTION_DECL,
1613 get_identifier (buf), TREE_TYPE (function));
1614 DECL_LANG_SPECIFIC (alias) = DECL_LANG_SPECIFIC (function);
1615 lang_hooks.dup_lang_specific_decl (alias);
1616 DECL_CONTEXT (alias) = NULL_TREE;
1617 TREE_READONLY (alias) = TREE_READONLY (function);
1618 TREE_THIS_VOLATILE (alias) = TREE_THIS_VOLATILE (function);
1619 TREE_PUBLIC (alias) = 0;
1620
1621 DECL_EXTERNAL (alias) = 0;
1622 DECL_ARTIFICIAL (alias) = 1;
1623
1624 DECL_DECLARED_INLINE_P (alias) = 0;
1625 DECL_INITIAL (alias) = error_mark_node;
1626 DECL_ARGUMENTS (alias) = copy_list (DECL_ARGUMENTS (function));
1627
1628 TREE_ADDRESSABLE (alias) = 1;
1629 TREE_USED (alias) = 1;
1630 SET_DECL_ASSEMBLER_NAME (alias, DECL_NAME (alias));
1631
1632 if (!flag_syntax_only)
1633 {
1634 cgraph_node *aliasn;
1635 aliasn = cgraph_node::create_same_body_alias (alias, function);
1636 gcc_assert (aliasn != NULL);
1637 }
1638 return alias;
1639 }
1640
1641 /* Emit the definition of a D vtable thunk. */
1642
1643 static void
1644 finish_thunk (tree thunk, tree function)
1645 {
1646 /* Setup how D thunks are outputted. */
1647 int fixed_offset = -THUNK_LANG_OFFSET (thunk);
1648 bool this_adjusting = true;
1649 tree alias;
1650
1651 if (TARGET_USE_LOCAL_THUNK_ALIAS_P (function))
1652 alias = make_alias_for_thunk (function);
1653 else
1654 alias = function;
1655
1656 TREE_ADDRESSABLE (function) = 1;
1657 TREE_USED (function) = 1;
1658
1659 if (flag_syntax_only)
1660 {
1661 TREE_ASM_WRITTEN (thunk) = 1;
1662 return;
1663 }
1664
1665 if (TARGET_USE_LOCAL_THUNK_ALIAS_P (function)
1666 && targetm_common.have_named_sections)
1667 {
1668 tree fn = function;
1669 symtab_node *symbol = symtab_node::get (function);
1670
1671 if (symbol != NULL && symbol->alias)
1672 {
1673 if (symbol->analyzed)
1674 fn = symtab_node::get (function)->ultimate_alias_target ()->decl;
1675 else
1676 fn = symtab_node::get (function)->alias_target;
1677 }
1678 resolve_unique_section (fn, 0, flag_function_sections);
1679
1680 if (DECL_SECTION_NAME (fn) != NULL && DECL_ONE_ONLY (fn))
1681 {
1682 resolve_unique_section (thunk, 0, flag_function_sections);
1683
1684 /* Output the thunk into the same section as function. */
1685 set_decl_section_name (thunk, DECL_SECTION_NAME (fn));
1686 symtab_node::get (thunk)->implicit_section
1687 = symtab_node::get (fn)->implicit_section;
1688 }
1689 }
1690
1691 /* Set up cloned argument trees for the thunk. */
1692 tree t = NULL_TREE;
1693 for (tree a = DECL_ARGUMENTS (function); a; a = DECL_CHAIN (a))
1694 {
1695 tree x = copy_node (a);
1696 DECL_CHAIN (x) = t;
1697 DECL_CONTEXT (x) = thunk;
1698 SET_DECL_RTL (x, NULL);
1699 DECL_HAS_VALUE_EXPR_P (x) = 0;
1700 TREE_ADDRESSABLE (x) = 0;
1701 t = x;
1702 }
1703 DECL_ARGUMENTS (thunk) = nreverse (t);
1704 TREE_ASM_WRITTEN (thunk) = 1;
1705
1706 cgraph_node *funcn, *thunk_node;
1707
1708 funcn = cgraph_node::get_create (function);
1709 gcc_assert (funcn);
1710 thunk_node = funcn->create_thunk (thunk, thunk, this_adjusting,
1711 fixed_offset, 0, 0, 0, alias);
1712
1713 if (DECL_ONE_ONLY (function))
1714 thunk_node->add_to_same_comdat_group (funcn);
1715
1716 /* Target assemble_mi_thunk doesn't work across section boundaries
1717 on many targets, instead force thunk to be expanded in gimple. */
1718 if (DECL_EXTERNAL (function))
1719 {
1720 /* cgraph::expand_thunk writes over current_function_decl, so if this
1721 could ever be in use by the codegen pass, we want to know about it. */
1722 gcc_assert (current_function_decl == NULL_TREE);
1723
1724 if (!stdarg_p (TREE_TYPE (thunk)))
1725 {
1726 thunk_node->create_edge (funcn, NULL, thunk_node->count);
1727 thunk_node->expand_thunk (false, true);
1728 }
1729
1730 /* Tell the back-end to not bother inlining the function, this is
1731 assumed not to work as it could be referencing symbols outside
1732 of the current compilation unit. */
1733 DECL_UNINLINABLE (function) = 1;
1734 }
1735 }
1736
1737 /* Return a thunk to DECL. Thunks adjust the incoming `this' pointer by OFFSET.
1738 Adjustor thunks are created and pointers to them stored in the method entries
1739 in the vtable in order to set the this pointer to the start of the object
1740 instance corresponding to the implementing method. */
1741
1742 tree
1743 make_thunk (FuncDeclaration *decl, int offset)
1744 {
1745 tree function = get_symbol_decl (decl);
1746
1747 if (!DECL_ARGUMENTS (function) || !DECL_RESULT (function))
1748 {
1749 /* Compile the function body before generating the thunk, this is done
1750 even if the decl is external to the current module. */
1751 if (decl->fbody)
1752 build_decl_tree (decl);
1753 else
1754 {
1755 /* Build parameters for functions that are not being compiled,
1756 so that they can be correctly cloned in finish_thunk. */
1757 tree fntype = TREE_TYPE (function);
1758 tree params = NULL_TREE;
1759
1760 for (tree t = TYPE_ARG_TYPES (fntype); t; t = TREE_CHAIN (t))
1761 {
1762 if (t == void_list_node)
1763 break;
1764
1765 tree param = build_decl (DECL_SOURCE_LOCATION (function),
1766 PARM_DECL, NULL_TREE, TREE_VALUE (t));
1767 DECL_ARG_TYPE (param) = TREE_TYPE (param);
1768 DECL_ARTIFICIAL (param) = 1;
1769 DECL_IGNORED_P (param) = 1;
1770 DECL_CONTEXT (param) = function;
1771 params = chainon (params, param);
1772 }
1773
1774 DECL_ARGUMENTS (function) = params;
1775
1776 /* Also build the result decl, which is needed when force creating
1777 the thunk in gimple inside cgraph_node::expand_thunk. */
1778 tree resdecl = build_decl (DECL_SOURCE_LOCATION (function),
1779 RESULT_DECL, NULL_TREE,
1780 TREE_TYPE (fntype));
1781 DECL_ARTIFICIAL (resdecl) = 1;
1782 DECL_IGNORED_P (resdecl) = 1;
1783 DECL_CONTEXT (resdecl) = function;
1784 DECL_RESULT (function) = resdecl;
1785 }
1786 }
1787
1788 /* Don't build the thunk if the compilation step failed. */
1789 if (global.errors)
1790 return error_mark_node;
1791
1792 /* See if we already have the thunk in question. */
1793 for (tree t = DECL_LANG_THUNKS (function); t; t = DECL_CHAIN (t))
1794 {
1795 if (THUNK_LANG_OFFSET (t) == offset)
1796 return t;
1797 }
1798
1799 tree thunk = build_decl (DECL_SOURCE_LOCATION (function),
1800 FUNCTION_DECL, NULL_TREE, TREE_TYPE (function));
1801 DECL_LANG_SPECIFIC (thunk) = DECL_LANG_SPECIFIC (function);
1802 lang_hooks.dup_lang_specific_decl (thunk);
1803 THUNK_LANG_OFFSET (thunk) = offset;
1804
1805 TREE_READONLY (thunk) = TREE_READONLY (function);
1806 TREE_THIS_VOLATILE (thunk) = TREE_THIS_VOLATILE (function);
1807 TREE_NOTHROW (thunk) = TREE_NOTHROW (function);
1808
1809 DECL_CONTEXT (thunk) = d_decl_context (decl);
1810
1811 /* Thunks inherit the public access of the function they are targetting.
1812 When the function is outside the current compilation unit however, then the
1813 thunk must be kept private to not conflict. */
1814 TREE_PUBLIC (thunk) = TREE_PUBLIC (function) && !DECL_EXTERNAL (function);
1815
1816 DECL_EXTERNAL (thunk) = 0;
1817
1818 /* Thunks are always addressable. */
1819 TREE_ADDRESSABLE (thunk) = 1;
1820 TREE_USED (thunk) = 1;
1821 DECL_ARTIFICIAL (thunk) = 1;
1822 DECL_DECLARED_INLINE_P (thunk) = 0;
1823
1824 DECL_VISIBILITY (thunk) = DECL_VISIBILITY (function);
1825 DECL_COMDAT (thunk) = DECL_COMDAT (function);
1826 DECL_WEAK (thunk) = DECL_WEAK (function);
1827
1828 tree target_name = DECL_ASSEMBLER_NAME (function);
1829 unsigned identlen = IDENTIFIER_LENGTH (target_name) + 14;
1830 const char *ident = XNEWVEC (const char, identlen);
1831 snprintf (CONST_CAST (char *, ident), identlen,
1832 "_DT%u%s", offset, IDENTIFIER_POINTER (target_name));
1833
1834 DECL_NAME (thunk) = get_identifier (ident);
1835 SET_DECL_ASSEMBLER_NAME (thunk, DECL_NAME (thunk));
1836
1837 d_keep (thunk);
1838
1839 finish_thunk (thunk, function);
1840
1841 /* Add it to the list of thunks associated with the function. */
1842 DECL_LANG_THUNKS (thunk) = NULL_TREE;
1843 DECL_CHAIN (thunk) = DECL_LANG_THUNKS (function);
1844 DECL_LANG_THUNKS (function) = thunk;
1845
1846 return thunk;
1847 }
1848
1849 /* Create the FUNCTION_DECL for a function definition.
1850 This function creates a binding context for the function body
1851 as well as setting up the FUNCTION_DECL in current_function_decl.
1852 Returns the previous function context if it was already set. */
1853
1854 tree
1855 start_function (FuncDeclaration *fd)
1856 {
1857 tree fndecl = get_symbol_decl (fd);
1858
1859 /* Function has been defined, check now whether we intend to send it to
1860 object file, or it really is extern. Such as inlinable functions from
1861 modules not in this compilation, or thunk aliases. */
1862 TemplateInstance *ti = fd->isInstantiated ();
1863 if (ti && ti->needsCodegen ())
1864 {
1865 /* Warn about templates instantiated in this compilation. */
1866 if (ti == fd->parent)
1867 {
1868 warning (OPT_Wtemplates, "%s %qs instantiated",
1869 ti->kind (), ti->toPrettyChars (false));
1870 }
1871
1872 DECL_EXTERNAL (fndecl) = 0;
1873 }
1874 else
1875 {
1876 Module *md = fd->getModule ();
1877 if (md && md->isRoot ())
1878 DECL_EXTERNAL (fndecl) = 0;
1879 }
1880
1881 DECL_INITIAL (fndecl) = error_mark_node;
1882
1883 /* Add this decl to the current binding level. */
1884 d_pushdecl (fndecl);
1885
1886 /* Save the current function context. */
1887 tree old_context = current_function_decl;
1888
1889 if (old_context)
1890 push_function_context ();
1891
1892 /* Let GCC know the current scope is this function. */
1893 current_function_decl = fndecl;
1894
1895 tree restype = TREE_TYPE (TREE_TYPE (fndecl));
1896 tree resdecl = build_decl (make_location_t (fd->loc), RESULT_DECL,
1897 NULL_TREE, restype);
1898
1899 DECL_RESULT (fndecl) = resdecl;
1900 DECL_CONTEXT (resdecl) = fndecl;
1901 DECL_ARTIFICIAL (resdecl) = 1;
1902 DECL_IGNORED_P (resdecl) = 1;
1903
1904 /* Initialize the RTL code for the function. */
1905 allocate_struct_function (fndecl, false);
1906
1907 /* Store the end of the function. */
1908 if (fd->endloc.filename)
1909 cfun->function_end_locus = make_location_t (fd->endloc);
1910 else
1911 cfun->function_end_locus = DECL_SOURCE_LOCATION (fndecl);
1912
1913 cfun->language = ggc_cleared_alloc<language_function> ();
1914 cfun->language->function = fd;
1915
1916 /* Default chain value is 'null' unless parent found. */
1917 cfun->language->static_chain = null_pointer_node;
1918
1919 /* Find module for this function. */
1920 for (Dsymbol *p = fd->parent; p != NULL; p = p->parent)
1921 {
1922 cfun->language->module = p->isModule ();
1923 if (cfun->language->module)
1924 break;
1925 }
1926 gcc_assert (cfun->language->module != NULL);
1927
1928 /* Begin the statement tree for this function. */
1929 push_stmt_list ();
1930 push_binding_level (level_function);
1931
1932 return old_context;
1933 }
1934
1935 /* Finish up a function declaration and compile that function all
1936 the way to assembler language output. The free the storage for
1937 the function definition. Restores the previous function context. */
1938
1939 void
1940 finish_function (tree old_context)
1941 {
1942 tree fndecl = current_function_decl;
1943
1944 /* Tie off the statement tree for this function. */
1945 tree block = pop_binding_level ();
1946 tree body = pop_stmt_list ();
1947 tree bind = build3 (BIND_EXPR, void_type_node,
1948 BLOCK_VARS (block), body, block);
1949
1950 gcc_assert (vec_safe_is_empty (d_function_chain->stmt_list));
1951
1952 /* Back-end expects a statement list to come from somewhere, however
1953 pop_stmt_list returns expressions when there is a single statement.
1954 So here we create a statement list unconditionally. */
1955 if (TREE_CODE (body) != STATEMENT_LIST)
1956 {
1957 tree stmtlist = alloc_stmt_list ();
1958 append_to_statement_list_force (body, &stmtlist);
1959 BIND_EXPR_BODY (bind) = stmtlist;
1960 }
1961 else if (!STATEMENT_LIST_HEAD (body))
1962 {
1963 /* For empty functions add a void return. */
1964 append_to_statement_list_force (return_expr (NULL_TREE), &body);
1965 }
1966
1967 DECL_SAVED_TREE (fndecl) = bind;
1968
1969 if (!errorcount && !global.errors)
1970 {
1971 /* Dump the D-specific tree IR. */
1972 dump_function (TDI_original, fndecl);
1973
1974 cgraph_node::finalize_function (fndecl, true);
1975 }
1976
1977 /* We're leaving the context of this function, so free it. */
1978 ggc_free (cfun->language);
1979 cfun->language = NULL;
1980 set_cfun (NULL);
1981
1982 if (old_context)
1983 pop_function_context ();
1984
1985 current_function_decl = old_context;
1986 }
1987
1988 /* Mark DECL, which is a VAR_DECL or FUNCTION_DECL as a symbol that
1989 must be emitted in this, output module. */
1990
1991 void
1992 mark_needed (tree decl)
1993 {
1994 TREE_USED (decl) = 1;
1995
1996 if (TREE_CODE (decl) == FUNCTION_DECL)
1997 {
1998 struct cgraph_node *node = cgraph_node::get_create (decl);
1999 node->forced_by_abi = true;
2000 }
2001 else if (VAR_P (decl))
2002 {
2003 struct varpool_node *node = varpool_node::get_create (decl);
2004 node->forced_by_abi = true;
2005 }
2006 }
2007
2008 /* Get the offset to the BC's vtbl[] initializer from the start of CD.
2009 Returns "~0u" if the base class is not found in any vtable interfaces. */
2010
2011 unsigned
2012 base_vtable_offset (ClassDeclaration *cd, BaseClass *bc)
2013 {
2014 unsigned csymoffset = Target::classinfosize;
2015 unsigned interfacesize = int_size_in_bytes (vtbl_interface_type_node);
2016 csymoffset += cd->vtblInterfaces->length * interfacesize;
2017
2018 for (size_t i = 0; i < cd->vtblInterfaces->length; i++)
2019 {
2020 BaseClass *b = (*cd->vtblInterfaces)[i];
2021 if (b == bc)
2022 return csymoffset;
2023 csymoffset += b->sym->vtbl.length * Target::ptrsize;
2024 }
2025
2026 /* Check all overriding interface vtbl[]s. */
2027 for (ClassDeclaration *cd2 = cd->baseClass; cd2; cd2 = cd2->baseClass)
2028 {
2029 for (size_t k = 0; k < cd2->vtblInterfaces->length; k++)
2030 {
2031 BaseClass *bs = (*cd2->vtblInterfaces)[k];
2032 if (bs->fillVtbl (cd, NULL, 0))
2033 {
2034 if (bc == bs)
2035 return csymoffset;
2036 csymoffset += bs->sym->vtbl.length * Target::ptrsize;
2037 }
2038 }
2039 }
2040
2041 return ~0u;
2042 }
2043
2044 /* Get the VAR_DECL of the vtable symbol for DECL. If this does not yet exist,
2045 create it. The vtable is accessible via ClassInfo, but since it is needed
2046 frequently (like for rtti comparisons), make it directly accessible. */
2047
2048 tree
2049 get_vtable_decl (ClassDeclaration *decl)
2050 {
2051 if (decl->vtblsym)
2052 return decl->vtblsym;
2053
2054 tree ident = mangle_internal_decl (decl, "__vtbl", "Z");
2055 /* Note: Using a static array type for the VAR_DECL, the DECL_INITIAL value
2056 will have a different type. However the back-end seems to accept this. */
2057 tree type = build_ctype (Type::tvoidptr->sarrayOf (decl->vtbl.length));
2058
2059 decl->vtblsym = declare_extern_var (ident, type);
2060 DECL_LANG_SPECIFIC (decl->vtblsym) = build_lang_decl (NULL);
2061
2062 /* Class is a reference, want the record type. */
2063 DECL_CONTEXT (decl->vtblsym) = TREE_TYPE (build_ctype (decl->type));
2064 TREE_READONLY (decl->vtblsym) = 1;
2065 DECL_VIRTUAL_P (decl->vtblsym) = 1;
2066
2067 SET_DECL_ALIGN (decl->vtblsym, TARGET_VTABLE_ENTRY_ALIGN);
2068 DECL_USER_ALIGN (decl->vtblsym) = true;
2069
2070 return decl->vtblsym;
2071 }
2072
2073 /* Helper function of build_class_instance. Find the field inside aggregate
2074 TYPE identified by IDENT at field OFFSET. */
2075
2076 static tree
2077 find_aggregate_field (tree type, tree ident, tree offset)
2078 {
2079 tree fields = TYPE_FIELDS (type);
2080
2081 for (tree field = fields; field != NULL_TREE; field = TREE_CHAIN (field))
2082 {
2083 if (DECL_NAME (field) == NULL_TREE
2084 && RECORD_OR_UNION_TYPE_P (TREE_TYPE (field))
2085 && ANON_AGGR_TYPE_P (TREE_TYPE (field)))
2086 {
2087 /* Search nesting anonymous structs and unions. */
2088 tree vfield = find_aggregate_field (TREE_TYPE (field),
2089 ident, offset);
2090 if (vfield != NULL_TREE)
2091 return vfield;
2092 }
2093 else if (DECL_NAME (field) == ident
2094 && (offset == NULL_TREE
2095 || DECL_FIELD_OFFSET (field) == offset))
2096 {
2097 /* Found matching field at offset. */
2098 return field;
2099 }
2100 }
2101
2102 return NULL_TREE;
2103 }
2104
2105 /* Helper function of build_new_class_expr. Return a constructor that matches
2106 the layout of the class expression EXP. */
2107
2108 static tree
2109 build_class_instance (ClassReferenceExp *exp)
2110 {
2111 ClassDeclaration *cd = exp->originalClass ();
2112 tree type = TREE_TYPE (build_ctype (exp->value->stype));
2113 vec<constructor_elt, va_gc> *ve = NULL;
2114
2115 /* The set base vtable field. */
2116 tree vptr = build_address (get_vtable_decl (cd));
2117 CONSTRUCTOR_APPEND_ELT (ve, TYPE_FIELDS (type), vptr);
2118
2119 /* Go through the inheritance graph from top to bottom. This will add all
2120 values to the constructor out of order, however build_struct_literal
2121 will re-order all values before returning the finished literal. */
2122 for (ClassDeclaration *bcd = cd; bcd != NULL; bcd = bcd->baseClass)
2123 {
2124 /* Anonymous vtable interface fields are laid out before the fields of
2125 each class. The interface offset is used to determine where to put
2126 the classinfo offset reference. */
2127 for (size_t i = 0; i < bcd->vtblInterfaces->length; i++)
2128 {
2129 BaseClass *bc = (*bcd->vtblInterfaces)[i];
2130
2131 for (ClassDeclaration *cd2 = cd; 1; cd2 = cd2->baseClass)
2132 {
2133 gcc_assert (cd2 != NULL);
2134
2135 unsigned csymoffset = base_vtable_offset (cd2, bc);
2136 /* If the base class vtable was found. */
2137 if (csymoffset != ~0u)
2138 {
2139 tree csym = build_address (get_classinfo_decl (cd2));
2140 csym = build_offset (csym, size_int (csymoffset));
2141
2142 tree field = find_aggregate_field (type, NULL_TREE,
2143 size_int (bc->offset));
2144 gcc_assert (field != NULL_TREE);
2145
2146 CONSTRUCTOR_APPEND_ELT (ve, field, csym);
2147 break;
2148 }
2149 }
2150 }
2151
2152 /* Generate initial values of all fields owned by current class.
2153 Use both the name and offset to find the right field. */
2154 for (size_t i = 0; i < bcd->fields.length; i++)
2155 {
2156 VarDeclaration *vfield = bcd->fields[i];
2157 int index = exp->findFieldIndexByName (vfield);
2158 gcc_assert (index != -1);
2159
2160 Expression *value = (*exp->value->elements)[index];
2161 if (!value)
2162 continue;
2163
2164 /* Use find_aggregate_field to get the overridden field decl,
2165 instead of the field associated with the base class. */
2166 tree field = get_symbol_decl (bcd->fields[i]);
2167 field = find_aggregate_field (type, DECL_NAME (field),
2168 DECL_FIELD_OFFSET (field));
2169 gcc_assert (field != NULL_TREE);
2170
2171 CONSTRUCTOR_APPEND_ELT (ve, field, build_expr (value, true));
2172 }
2173 }
2174
2175 return build_struct_literal (type, ve);
2176 }
2177
2178 /* Get the VAR_DECL of a class instance representing EXPR as static data.
2179 If this does not yet exist, create it. This is used to support initializing
2180 a static variable that is of a class type using values known during CTFE.
2181 In user code, it is analogous to the following code snippet.
2182
2183 enum E = new C(1, 2, 3);
2184
2185 That we write the contents of `C(1, 2, 3)' to static data is only a compiler
2186 implementation detail. The initialization of these symbols could be done at
2187 run-time using during as part of the module initialization or shared static
2188 constructors phase of run-time start-up - whichever comes after `gc_init()'.
2189 And infact that would be the better thing to do here eventually. */
2190
2191 tree
2192 build_new_class_expr (ClassReferenceExp *expr)
2193 {
2194 if (expr->value->sym)
2195 return expr->value->sym;
2196
2197 /* Build the reference symbol. */
2198 tree type = build_ctype (expr->value->stype);
2199 expr->value->sym = build_artificial_decl (TREE_TYPE (type), NULL_TREE, "C");
2200
2201 DECL_INITIAL (expr->value->sym) = build_class_instance (expr);
2202 d_pushdecl (expr->value->sym);
2203 rest_of_decl_compilation (expr->value->sym, 1, 0);
2204
2205 return expr->value->sym;
2206 }
2207
2208 /* Get the VAR_DECL of the static initializer symbol for the struct/class DECL.
2209 If this does not yet exist, create it. The static initializer data is
2210 accessible via TypeInfo, and is also used in 'new class' and default
2211 initializing struct literals. */
2212
2213 tree
2214 aggregate_initializer_decl (AggregateDeclaration *decl)
2215 {
2216 if (decl->sinit)
2217 return decl->sinit;
2218
2219 /* Class is a reference, want the record type. */
2220 tree type = build_ctype (decl->type);
2221 StructDeclaration *sd = decl->isStructDeclaration ();
2222 if (!sd)
2223 type = TREE_TYPE (type);
2224
2225 tree ident = mangle_internal_decl (decl, "__init", "Z");
2226
2227 decl->sinit = declare_extern_var (ident, type);
2228 DECL_LANG_SPECIFIC (decl->sinit) = build_lang_decl (NULL);
2229
2230 DECL_CONTEXT (decl->sinit) = type;
2231 TREE_READONLY (decl->sinit) = 1;
2232
2233 /* Honor struct alignment set by user. */
2234 if (sd && sd->alignment != STRUCTALIGN_DEFAULT)
2235 {
2236 SET_DECL_ALIGN (decl->sinit, sd->alignment * BITS_PER_UNIT);
2237 DECL_USER_ALIGN (decl->sinit) = true;
2238 }
2239
2240 return decl->sinit;
2241 }
2242
2243 /* Generate the data for the static initializer. */
2244
2245 tree
2246 layout_class_initializer (ClassDeclaration *cd)
2247 {
2248 NewExp *ne = NewExp::create (cd->loc, NULL, NULL, cd->type, NULL);
2249 ne->type = cd->type;
2250
2251 Expression *e = ne->ctfeInterpret ();
2252 gcc_assert (e->op == TOKclassreference);
2253
2254 return build_class_instance ((ClassReferenceExp *) e);
2255 }
2256
2257 tree
2258 layout_struct_initializer (StructDeclaration *sd)
2259 {
2260 StructLiteralExp *sle = StructLiteralExp::create (sd->loc, sd, NULL);
2261
2262 if (!sd->fill (sd->loc, sle->elements, true))
2263 gcc_unreachable ();
2264
2265 sle->type = sd->type;
2266 return build_expr (sle, true);
2267 }
2268
2269 /* Get the VAR_DECL of the static initializer symbol for the enum DECL.
2270 If this does not yet exist, create it. The static initializer data is
2271 accessible via TypeInfo_Enum, but the field member type is a byte[] that
2272 requires a pointer to a symbol reference. */
2273
2274 tree
2275 enum_initializer_decl (EnumDeclaration *decl)
2276 {
2277 if (decl->sinit)
2278 return decl->sinit;
2279
2280 tree type = build_ctype (decl->type);
2281
2282 Identifier *ident_save = decl->ident;
2283 if (!decl->ident)
2284 decl->ident = Identifier::generateId ("__enum");
2285 tree ident = mangle_internal_decl (decl, "__init", "Z");
2286 decl->ident = ident_save;
2287
2288 decl->sinit = declare_extern_var (ident, type);
2289 DECL_LANG_SPECIFIC (decl->sinit) = build_lang_decl (NULL);
2290
2291 DECL_CONTEXT (decl->sinit) = d_decl_context (decl);
2292 TREE_READONLY (decl->sinit) = 1;
2293
2294 return decl->sinit;
2295 }
2296
2297 /* Return an anonymous static variable of type TYPE, initialized with INIT,
2298 and optionally prefixing the name with PREFIX. */
2299
2300 tree
2301 build_artificial_decl (tree type, tree init, const char *prefix)
2302 {
2303 tree decl = build_decl (UNKNOWN_LOCATION, VAR_DECL, NULL_TREE, type);
2304 const char *name = prefix ? prefix : "___s";
2305 char *label;
2306
2307 ASM_FORMAT_PRIVATE_NAME (label, name, DECL_UID (decl));
2308 SET_DECL_ASSEMBLER_NAME (decl, get_identifier (label));
2309 DECL_NAME (decl) = DECL_ASSEMBLER_NAME (decl);
2310
2311 TREE_PUBLIC (decl) = 0;
2312 TREE_STATIC (decl) = 1;
2313 TREE_USED (decl) = 1;
2314 DECL_IGNORED_P (decl) = 1;
2315 DECL_ARTIFICIAL (decl) = 1;
2316
2317 /* Perhaps at some point the initializer constant should be hashed
2318 to remove duplicates. */
2319 DECL_INITIAL (decl) = init;
2320
2321 return decl;
2322 }
2323
2324 /* Build TYPE_DECL for the declaration DSYM. */
2325
2326 void
2327 build_type_decl (tree type, Dsymbol *dsym)
2328 {
2329 if (TYPE_STUB_DECL (type))
2330 return;
2331
2332 gcc_assert (!POINTER_TYPE_P (type));
2333
2334 /* If a templated type, use the template instance name, as that includes all
2335 template parameters. */
2336 const char *name = dsym->parent->isTemplateInstance ()
2337 ? ((TemplateInstance *) dsym->parent)->toChars () : dsym->ident->toChars ();
2338
2339 tree decl = build_decl (make_location_t (dsym->loc), TYPE_DECL,
2340 get_identifier (name), type);
2341 SET_DECL_ASSEMBLER_NAME (decl, get_identifier (d_mangle_decl (dsym)));
2342 TREE_PUBLIC (decl) = 1;
2343 DECL_ARTIFICIAL (decl) = 1;
2344 DECL_CONTEXT (decl) = d_decl_context (dsym);
2345
2346 TYPE_CONTEXT (type) = DECL_CONTEXT (decl);
2347 TYPE_NAME (type) = decl;
2348
2349 /* Not sure if there is a need for separate TYPE_DECLs in
2350 TYPE_NAME and TYPE_STUB_DECL. */
2351 if (TREE_CODE (type) == ENUMERAL_TYPE || RECORD_OR_UNION_TYPE_P (type))
2352 TYPE_STUB_DECL (type) = decl;
2353
2354 rest_of_decl_compilation (decl, SCOPE_FILE_SCOPE_P (decl), 0);
2355 }
2356
2357 /* Create a declaration for field NAME of a given TYPE, setting the flags
2358 for whether the field is ARTIFICIAL and/or IGNORED. */
2359
2360 tree
2361 create_field_decl (tree type, const char *name, int artificial, int ignored)
2362 {
2363 tree decl = build_decl (input_location, FIELD_DECL,
2364 name ? get_identifier (name) : NULL_TREE, type);
2365 DECL_ARTIFICIAL (decl) = artificial;
2366 DECL_IGNORED_P (decl) = ignored;
2367
2368 return decl;
2369 }
2370
2371 /* Return the COMDAT group into which DECL should be placed. */
2372
2373 static tree
2374 d_comdat_group (tree decl)
2375 {
2376 /* If already part of a comdat group, use that. */
2377 if (DECL_COMDAT_GROUP (decl))
2378 return DECL_COMDAT_GROUP (decl);
2379
2380 return DECL_ASSEMBLER_NAME (decl);
2381 }
2382
2383 /* Set DECL up to have the closest approximation of "initialized common"
2384 linkage available. */
2385
2386 void
2387 d_comdat_linkage (tree decl)
2388 {
2389 if (flag_weak)
2390 make_decl_one_only (decl, d_comdat_group (decl));
2391 else if (TREE_CODE (decl) == FUNCTION_DECL
2392 || (VAR_P (decl) && DECL_ARTIFICIAL (decl)))
2393 /* We can just emit function and compiler-generated variables statically;
2394 having multiple copies is (for the most part) only a waste of space. */
2395 TREE_PUBLIC (decl) = 0;
2396 else if (DECL_INITIAL (decl) == NULL_TREE
2397 || DECL_INITIAL (decl) == error_mark_node)
2398 /* Fallback, cannot have multiple copies. */
2399 DECL_COMMON (decl) = 1;
2400
2401 if (TREE_PUBLIC (decl))
2402 DECL_COMDAT (decl) = 1;
2403 }
2404
2405 /* Set DECL up to have the closest approximation of "linkonce" linkage. */
2406
2407 void
2408 d_linkonce_linkage (tree decl)
2409 {
2410 /* Weak definitions have to be public. */
2411 if (!TREE_PUBLIC (decl))
2412 return;
2413
2414 /* Necessary to allow DECL_ONE_ONLY or DECL_WEAK functions to be inlined. */
2415 if (TREE_CODE (decl) == FUNCTION_DECL)
2416 DECL_DECLARED_INLINE_P (decl) = 1;
2417
2418 /* No weak support, fallback to COMDAT linkage. */
2419 if (!flag_weak)
2420 return d_comdat_linkage (decl);
2421
2422 make_decl_one_only (decl, d_comdat_group (decl));
2423 }