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