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