xref: /netbsd-src/external/gpl3/gcc.old/dist/gcc/d/decl.cc (revision 06dfa8449cb5e76c0044ec0f3badf7d5180af0f5)
1 /* decl.cc -- Lower D frontend declarations to GCC trees.
2    Copyright (C) 2006-2020 Free Software Foundation, Inc.
3 
4 GCC is free software; you can redistribute it and/or modify
5 it under the terms of the GNU General Public License as published by
6 the Free Software Foundation; either version 3, or (at your option)
7 any later version.
8 
9 GCC is distributed in the hope that it will be useful,
10 but WITHOUT ANY WARRANTY; without even the implied warranty of
11 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
12 GNU General Public License for more details.
13 
14 You should have received a copy of the GNU General Public License
15 along with GCC; see the file COPYING3.  If not see
16 <http://www.gnu.org/licenses/>.  */
17 
18 #include "config.h"
19 #include "system.h"
20 #include "coretypes.h"
21 
22 #include "dmd/aggregate.h"
23 #include "dmd/attrib.h"
24 #include "dmd/cond.h"
25 #include "dmd/ctfe.h"
26 #include "dmd/declaration.h"
27 #include "dmd/enum.h"
28 #include "dmd/errors.h"
29 #include "dmd/globals.h"
30 #include "dmd/hdrgen.h"
31 #include "dmd/identifier.h"
32 #include "dmd/import.h"
33 #include "dmd/init.h"
34 #include "dmd/mangle.h"
35 #include "dmd/module.h"
36 #include "dmd/nspace.h"
37 #include "dmd/target.h"
38 #include "dmd/template.h"
39 
40 #include "tree.h"
41 #include "tree-iterator.h"
42 #include "fold-const.h"
43 #include "diagnostic.h"
44 #include "langhooks.h"
45 #include "target.h"
46 #include "common/common-target.h"
47 #include "cgraph.h"
48 #include "toplev.h"
49 #include "stringpool.h"
50 #include "varasm.h"
51 #include "stor-layout.h"
52 #include "attribs.h"
53 #include "function.h"
54 #include "debug.h"
55 #include "tree-pretty-print.h"
56 
57 #include "d-tree.h"
58 
59 
60 /* Return identifier for the external mangled name of DECL.  */
61 
62 const char *
63 d_mangle_decl (Dsymbol *decl)
64 {
65   if (decl->isFuncDeclaration ())
66     return mangleExact ((FuncDeclaration *)decl);
67   else
68     {
69       OutBuffer buf;
70       mangleToBuffer (decl, &buf);
71       return buf.extractString ();
72     }
73 }
74 
75 /* Generate a mangled identifier using NAME and SUFFIX, prefixed by the
76    assembler name for DECL.  */
77 
78 tree
79 mangle_internal_decl (Dsymbol *decl, const char *name, const char *suffix)
80 {
81   const char *prefix = d_mangle_decl (decl);
82   unsigned namelen = strlen (name);
83   unsigned buflen = (2 + strlen (prefix) + namelen + strlen (suffix)) * 2;
84   char *buf = (char *) alloca (buflen);
85 
86   snprintf (buf, buflen, "_D%s%u%s%s", prefix, namelen, name, suffix);
87   tree ident = get_identifier (buf);
88 
89   /* Symbol is not found in user code, but generate a readable name for it
90      anyway for debug and diagnostic reporting.  */
91   snprintf (buf, buflen, "%s.%s", decl->toPrettyChars (), name);
92   IDENTIFIER_PRETTY_NAME (ident) = get_identifier (buf);
93 
94   return ident;
95 }
96 
97 /* Returns true if DECL is from the gcc.attribute module.  */
98 
99 static bool
100 gcc_attribute_p (Dsymbol *decl)
101 {
102   ModuleDeclaration *md = decl->getModule ()->md;
103 
104   if (md && md->packages && md->packages->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:
129   DeclVisitor (void)
130   {
131     this->in_version_unittest_ = false;
132   }
133 
134   /* This should be overridden by each declaration class.  */
135 
136   void visit (Dsymbol *)
137   {
138   }
139 
140   /* Compile a D module, and all members of it.  */
141 
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 
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 
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 
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 
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 
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 
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 
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 
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 
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 
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 
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 
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 
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 
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 
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 
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 
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 	/* Return non-trivial structs by invisible reference.  */
967 	if (TREE_ADDRESSABLE (TREE_TYPE (resdecl)))
968 	  {
969 	    TREE_TYPE (resdecl) = build_reference_type (TREE_TYPE (resdecl));
970 	    DECL_BY_REFERENCE (resdecl) = 1;
971 	    TREE_ADDRESSABLE (resdecl) = 0;
972 	    relayout_decl (resdecl);
973 	  }
974 
975 	if (d->nrvo_var)
976 	  {
977 	    tree var = get_symbol_decl (d->nrvo_var);
978 
979 	    /* Copy name from VAR to RESULT.  */
980 	    DECL_NAME (resdecl) = DECL_NAME (var);
981 	    /* Don't forget that we take its address.  */
982 	    TREE_ADDRESSABLE (var) = 1;
983 
984 	    if (DECL_BY_REFERENCE (resdecl))
985 	      resdecl = build_deref (resdecl);
986 
987 	    SET_DECL_VALUE_EXPR (var, resdecl);
988 	    DECL_HAS_VALUE_EXPR_P (var) = 1;
989 	    SET_DECL_LANG_NRVO (var, resdecl);
990 	  }
991       }
992 
993     build_function_body (d);
994 
995     /* Initialize the _argptr variable.  */
996     if (d->v_argptr)
997       {
998 	tree body = pop_stmt_list ();
999 	tree var = get_decl_tree (d->v_argptr);
1000 	var = build_address (var);
1001 
1002 	tree init = build_call_expr (builtin_decl_explicit (BUILT_IN_VA_START),
1003 				     2, var, parm_decl);
1004 	declare_local_var (d->v_argptr);
1005 	add_stmt (init);
1006 
1007 	tree cleanup = build_call_expr (builtin_decl_explicit (BUILT_IN_VA_END),
1008 					1, var);
1009 	add_stmt (build2 (TRY_FINALLY_EXPR, void_type_node, body, cleanup));
1010       }
1011 
1012     finish_function (old_context);
1013 
1014     /* Maybe record the function against the current module.  */
1015     register_module_decl (d);
1016   }
1017 };
1018 
1019 /* Main entry point for the DeclVisitor interface to send
1020    the Declaration AST class D to GCC back-end.  */
1021 
1022 void
1023 build_decl_tree (Dsymbol *d)
1024 {
1025   location_t saved_location = input_location;
1026 
1027   /* Set input location, empty DECL_SOURCE_FILE can crash debug generator.  */
1028   if (d->loc.filename)
1029     input_location = make_location_t (d->loc);
1030   else
1031     input_location = make_location_t (Loc ("<no_file>", 1, 0));
1032 
1033   DeclVisitor v = DeclVisitor ();
1034   d->accept (&v);
1035 
1036   input_location = saved_location;
1037 }
1038 
1039 /* Return the decl for the symbol, create it if it doesn't already exist.  */
1040 
1041 tree
1042 get_symbol_decl (Declaration *decl)
1043 {
1044   if (decl->csym)
1045     return decl->csym;
1046 
1047   /* Deal with placeholder symbols immediately:
1048      SymbolDeclaration is used as a shell around an initializer symbol.  */
1049   SymbolDeclaration *sd = decl->isSymbolDeclaration ();
1050   if (sd)
1051     {
1052       decl->csym = aggregate_initializer_decl (sd->dsym);
1053       return decl->csym;
1054     }
1055 
1056   /* Global static TypeInfo declaration.  */
1057   if (decl->isTypeInfoDeclaration ())
1058     return get_typeinfo_decl ((TypeInfoDeclaration *) decl);
1059 
1060   /* FuncAliasDeclaration is used to import functions from another scope.  */
1061   FuncAliasDeclaration *fad = decl->isFuncAliasDeclaration ();
1062   if (fad)
1063     {
1064       decl->csym = get_symbol_decl (fad->funcalias);
1065       return decl->csym;
1066     }
1067 
1068   /* It is possible for a field declaration symbol to be requested
1069      before the parent type has been built.  */
1070   if (decl->isField ())
1071     {
1072       AggregateDeclaration *ad = decl->toParent ()->isAggregateDeclaration ();
1073       gcc_assert (ad != NULL);
1074 
1075       /* Finishing off the type should create the associated FIELD_DECL.  */
1076       build_ctype (ad->type);
1077       gcc_assert (decl->csym != NULL);
1078 
1079       return decl->csym;
1080     }
1081 
1082   /* Build the tree for the symbol.  */
1083   FuncDeclaration *fd = decl->isFuncDeclaration ();
1084   if (fd)
1085     {
1086       /* Run full semantic on functions we need to know about.  */
1087       if (!fd->functionSemantic ())
1088 	{
1089 	  decl->csym = error_mark_node;
1090 	  return decl->csym;
1091 	}
1092 
1093       decl->csym = build_decl (make_location_t (decl->loc), FUNCTION_DECL,
1094 			       get_identifier (decl->ident->toChars ()),
1095 			       NULL_TREE);
1096 
1097       /* Set function type afterwards as there could be self references.  */
1098       TREE_TYPE (decl->csym) = build_ctype (fd->type);
1099 
1100       /* Set DECL_INITIAL now if the function has a definition.  */
1101       if (fd->fbody)
1102 	DECL_INITIAL (decl->csym) = error_mark_node;
1103       else
1104 	DECL_EXTERNAL (decl->csym) = 1;
1105     }
1106   else
1107     {
1108       /* Build the variable declaration.  */
1109       VarDeclaration *vd = decl->isVarDeclaration ();
1110       gcc_assert (vd != NULL);
1111 
1112       tree_code code = vd->isParameter () ? PARM_DECL
1113 	: !vd->canTakeAddressOf () ? CONST_DECL
1114 	: VAR_DECL;
1115       decl->csym = build_decl (make_location_t (decl->loc), code,
1116 			       get_identifier (decl->ident->toChars ()),
1117 			       declaration_type (vd));
1118 
1119       /* If any alignment was set on the declaration.  */
1120       if (vd->alignment != STRUCTALIGN_DEFAULT)
1121 	{
1122 	  SET_DECL_ALIGN (decl->csym, vd->alignment * BITS_PER_UNIT);
1123 	  DECL_USER_ALIGN (decl->csym) = 1;
1124 	}
1125 
1126       if (vd->storage_class & STCextern)
1127 	DECL_EXTERNAL (decl->csym) = 1;
1128 
1129       /* CONST_DECL was initially intended for enumerals and may be used for
1130 	 scalars in general, but not for aggregates.  Here a non-constant
1131 	 value is generated anyway so as the CONST_DECL only serves as a
1132 	 placeholder for the value, however the DECL itself should never be
1133 	 referenced in any generated code, or passed to the back-end.  */
1134       if (vd->storage_class & STCmanifest)
1135 	{
1136 	  /* Cannot make an expression out of a void initializer.  */
1137 	  if (vd->_init && !vd->_init->isVoidInitializer ())
1138 	    {
1139 	      Expression *ie = initializerToExpression (vd->_init);
1140 
1141 	      if (!vd->type->isscalar ())
1142 		DECL_INITIAL (decl->csym) = build_expr (ie, false);
1143 	      else
1144 		DECL_INITIAL (decl->csym) = build_expr (ie, true);
1145 	    }
1146 	}
1147     }
1148 
1149   /* Set the declaration mangled identifier if static.  */
1150   if (decl->isCodeseg () || decl->isDataseg ())
1151     {
1152       tree mangled_name;
1153 
1154       if (decl->mangleOverride)
1155 	mangled_name = get_identifier (decl->mangleOverride);
1156       else
1157 	mangled_name = get_identifier (d_mangle_decl (decl));
1158 
1159       mangled_name = targetm.mangle_decl_assembler_name (decl->csym,
1160 							 mangled_name);
1161       /* The frontend doesn't handle duplicate definitions of unused symbols
1162 	 with the same mangle.  So a check is done here instead.  */
1163       if (IDENTIFIER_DSYMBOL (mangled_name))
1164 	{
1165 	  Declaration *other = IDENTIFIER_DSYMBOL (mangled_name);
1166 	  tree olddecl = decl->csym;
1167 	  decl->csym = get_symbol_decl (other);
1168 
1169 	  /* The current declaration is a prototype or marked extern, merge
1170 	     applied user attributes and return.  */
1171 	  if (DECL_EXTERNAL (olddecl) && !DECL_INITIAL (olddecl))
1172 	    {
1173 	      apply_user_attributes (decl, decl->csym);
1174 	      return decl->csym;
1175 	    }
1176 	  /* The previous declaration is a prototype or marked extern, set the
1177 	     current declaration as the main reference of the symbol.  */
1178 	  else if (DECL_EXTERNAL (decl->csym) && !DECL_INITIAL (decl->csym))
1179 	    {
1180 	      IDENTIFIER_DSYMBOL (mangled_name) = decl;
1181 	      DECL_EXTERNAL (decl->csym) = 0;
1182 	    }
1183 	  /* Non-extern, non-templated decls shouldn't be defined twice.  */
1184 	  else if (!decl->isInstantiated ())
1185 	    ScopeDsymbol::multiplyDefined (decl->loc, decl, other);
1186 	}
1187       else
1188 	{
1189 	  IDENTIFIER_PRETTY_NAME (mangled_name)
1190 	    = get_identifier (decl->toPrettyChars (true));
1191 	  IDENTIFIER_DSYMBOL (mangled_name) = decl;
1192 
1193 	  SET_DECL_ASSEMBLER_NAME (decl->csym, mangled_name);
1194 	}
1195     }
1196 
1197   DECL_LANG_SPECIFIC (decl->csym) = build_lang_decl (decl);
1198   DECL_CONTEXT (decl->csym) = d_decl_context (decl);
1199 
1200   if (TREE_CODE (decl->csym) == PARM_DECL)
1201     {
1202       /* Pass non-trivial structs by invisible reference.  */
1203       if (TREE_ADDRESSABLE (TREE_TYPE (decl->csym)))
1204 	{
1205 	  tree argtype = build_reference_type (TREE_TYPE (decl->csym));
1206 	  argtype = build_qualified_type (argtype, TYPE_QUAL_RESTRICT);
1207 	  gcc_assert (!DECL_BY_REFERENCE (decl->csym));
1208 	  TREE_TYPE (decl->csym) = argtype;
1209 	  DECL_BY_REFERENCE (decl->csym) = 1;
1210 	  TREE_ADDRESSABLE (decl->csym) = 0;
1211 	  relayout_decl (decl->csym);
1212 	  decl->storage_class |= STCref;
1213 	}
1214 
1215       DECL_ARG_TYPE (decl->csym) = TREE_TYPE (decl->csym);
1216       gcc_assert (TREE_CODE (DECL_CONTEXT (decl->csym)) == FUNCTION_DECL);
1217     }
1218   else if (TREE_CODE (decl->csym) == CONST_DECL)
1219     {
1220       /* Manifest constants have no address in memory.  */
1221       TREE_CONSTANT (decl->csym) = 1;
1222       TREE_READONLY (decl->csym) = 1;
1223     }
1224   else if (TREE_CODE (decl->csym) == FUNCTION_DECL)
1225     {
1226       /* The real function type may differ from its declaration.  */
1227       tree fntype = TREE_TYPE (decl->csym);
1228       tree newfntype = NULL_TREE;
1229 
1230       if (fd->isNested ())
1231 	{
1232 	  /* Add an extra argument for the frame/closure pointer, this is also
1233 	     required to be compatible with D delegates.  */
1234 	  newfntype = build_vthis_function (void_type_node, fntype);
1235 	}
1236       else if (fd->isThis ())
1237 	{
1238 	  /* Add an extra argument for the 'this' parameter.  The handle type is
1239 	     used even if there is no debug info.  It is needed to make sure
1240 	     virtual member functions are not called statically.  */
1241 	  AggregateDeclaration *ad = fd->isMember2 ();
1242 	  tree handle = build_ctype (ad->handleType ());
1243 
1244 	  /* If handle is a pointer type, get record type.  */
1245 	  if (!ad->isStructDeclaration ())
1246 	    handle = TREE_TYPE (handle);
1247 
1248 	  newfntype = build_vthis_function (handle, fntype);
1249 
1250 	  /* Set the vindex on virtual functions.  */
1251 	  if (fd->isVirtual () && fd->vtblIndex != -1)
1252 	    {
1253 	      DECL_VINDEX (decl->csym) = size_int (fd->vtblIndex);
1254 	      DECL_VIRTUAL_P (decl->csym) = 1;
1255 	    }
1256 
1257 	  /* Align method to the minimum boundary for target.  */
1258 	  SET_DECL_ALIGN (decl->csym, MINIMUM_METHOD_BOUNDARY);
1259 	}
1260       else if (fd->isMain () || fd->isCMain ())
1261 	{
1262 	  /* The main function is named 'D main' to distinguish from C main.  */
1263 	  if (fd->isMain ())
1264 	    DECL_NAME (decl->csym) = get_identifier (fd->toPrettyChars (true));
1265 
1266 	  /* 'void main' is implicitly converted to returning an int.  */
1267 	  newfntype = build_function_type (d_int_type, TYPE_ARG_TYPES (fntype));
1268 	}
1269 
1270       if (newfntype != NULL_TREE)
1271 	{
1272 	  /* Copy the old attributes from the original type.  */
1273 	  TYPE_ATTRIBUTES (newfntype) = TYPE_ATTRIBUTES (fntype);
1274 	  TYPE_LANG_SPECIFIC (newfntype) = TYPE_LANG_SPECIFIC (fntype);
1275 	  TREE_ADDRESSABLE (newfntype) = TREE_ADDRESSABLE (fntype);
1276 	  TREE_TYPE (decl->csym) = newfntype;
1277 	  d_keep (newfntype);
1278 	}
1279 
1280       /* Miscellaneous function flags.  */
1281       if (fd->isMember2 () || fd->isFuncLiteralDeclaration ())
1282 	{
1283 	  /* See grokmethod in cp/decl.c.  Maybe we shouldn't be setting inline
1284 	     flags without reason or proper handling.  */
1285 	  DECL_DECLARED_INLINE_P (decl->csym) = 1;
1286 	  DECL_NO_INLINE_WARNING_P (decl->csym) = 1;
1287 	}
1288 
1289       /* In [pragma/inline], functions decorated with 'pragma(inline)' affects
1290 	 whether they are inlined or not.  */
1291       if (fd->inlining == PINLINEalways)
1292 	DECL_DECLARED_INLINE_P (decl->csym) = 1;
1293       else if (fd->inlining == PINLINEnever)
1294 	DECL_UNINLINABLE (decl->csym) = 1;
1295 
1296       /* Function was declared 'naked'.  */
1297       if (fd->naked)
1298 	{
1299 	  insert_decl_attribute (decl->csym, "naked");
1300 	  DECL_NO_INSTRUMENT_FUNCTION_ENTRY_EXIT (decl->csym) = 1;
1301 	}
1302 
1303       /* Vector array operations are always compiler generated.  */
1304       if (fd->isArrayOp)
1305 	{
1306 	  TREE_PUBLIC (decl->csym) = 1;
1307 	  DECL_ARTIFICIAL (decl->csym) = 1;
1308 	  DECL_DECLARED_INLINE_P (decl->csym) = 1;
1309 	  d_comdat_linkage (decl->csym);
1310 	}
1311 
1312       /* And so are ensure and require contracts.  */
1313       if (fd->ident == Identifier::idPool ("ensure")
1314 	  || fd->ident == Identifier::idPool ("require"))
1315 	{
1316 	  DECL_ARTIFICIAL (decl->csym) = 1;
1317 	  TREE_PUBLIC (decl->csym) = 1;
1318 	}
1319 
1320       if (decl->storage_class & STCfinal)
1321 	DECL_FINAL_P (decl->csym) = 1;
1322 
1323       /* Check whether this function is expanded by the frontend.  */
1324       DECL_INTRINSIC_CODE (decl->csym) = INTRINSIC_NONE;
1325       maybe_set_intrinsic (fd);
1326 
1327       /* For nested functions in particular, unnest fndecl in the cgraph, as
1328 	 all static chain passing is handled by the front-end.  Do this even
1329 	 if we are not emitting the body.  */
1330       struct cgraph_node *node = cgraph_node::get_create (decl->csym);
1331       if (node->origin)
1332 	node->unnest ();
1333     }
1334 
1335   /* Mark compiler generated temporaries as artificial.  */
1336   if (decl->storage_class & STCtemp)
1337     DECL_ARTIFICIAL (decl->csym) = 1;
1338 
1339   /* Propagate shared on the decl.  */
1340   if (TYPE_SHARED (TREE_TYPE (decl->csym)))
1341     TREE_ADDRESSABLE (decl->csym) = 1;
1342 
1343   /* Symbol was marked volatile.  */
1344   if (decl->storage_class & STCvolatile)
1345     TREE_THIS_VOLATILE (decl->csym) = 1;
1346 
1347   /* Protection attributes are used by the debugger.  */
1348   if (decl->protection.kind == PROTprivate)
1349     TREE_PRIVATE (decl->csym) = 1;
1350   else if (decl->protection.kind == PROTprotected)
1351     TREE_PROTECTED (decl->csym) = 1;
1352 
1353   /* Likewise, so could the deprecated attribute.  */
1354   if (decl->storage_class & STCdeprecated)
1355     TREE_DEPRECATED (decl->csym) = 1;
1356 
1357 #if TARGET_DLLIMPORT_DECL_ATTRIBUTES
1358   /* Have to test for import first.  */
1359   if (decl->isImportedSymbol ())
1360     {
1361       insert_decl_attribute (decl->csym, "dllimport");
1362       DECL_DLLIMPORT_P (decl->csym) = 1;
1363     }
1364   else if (decl->isExport ())
1365     insert_decl_attribute (decl->csym, "dllexport");
1366 #endif
1367 
1368   if (decl->isDataseg () || decl->isCodeseg () || decl->isThreadlocal ())
1369     {
1370       /* Set TREE_PUBLIC by default, but allow private template to override.  */
1371       if (!fd || !fd->isNested ())
1372 	TREE_PUBLIC (decl->csym) = 1;
1373 
1374       TREE_STATIC (decl->csym) = 1;
1375       /* The decl has not been defined -- yet.  */
1376       DECL_EXTERNAL (decl->csym) = 1;
1377 
1378       if (decl->isInstantiated ())
1379 	d_linkonce_linkage (decl->csym);
1380     }
1381 
1382   /* Symbol is going in thread local storage.  */
1383   if (decl->isThreadlocal () && !DECL_ARTIFICIAL (decl->csym))
1384     {
1385       if (global.params.vtls)
1386 	message (decl->loc, "`%s` is thread local", decl->toChars ());
1387 
1388       set_decl_tls_model (decl->csym, decl_default_tls_model (decl->csym));
1389     }
1390 
1391   /* Apply any user attributes that may affect semantic meaning.  */
1392   apply_user_attributes (decl, decl->csym);
1393 
1394   /* %% Probably should be a little more intelligent about setting this.  */
1395   TREE_USED (decl->csym) = 1;
1396   d_keep (decl->csym);
1397 
1398   return decl->csym;
1399 }
1400 
1401 /* Returns a declaration for a VAR_DECL.  Used to create compiler-generated
1402    global variables.  */
1403 
1404 tree
1405 declare_extern_var (tree ident, tree type)
1406 {
1407   /* If the VAR_DECL has already been declared, return it.  */
1408   if (IDENTIFIER_DECL_TREE (ident))
1409     return IDENTIFIER_DECL_TREE (ident);
1410 
1411   tree name = IDENTIFIER_PRETTY_NAME (ident)
1412     ? IDENTIFIER_PRETTY_NAME (ident) : ident;
1413   tree decl = build_decl (input_location, VAR_DECL, name, type);
1414 
1415   IDENTIFIER_DECL_TREE (ident) = decl;
1416   d_keep (decl);
1417 
1418   SET_DECL_ASSEMBLER_NAME (decl, ident);
1419   DECL_ARTIFICIAL (decl) = 1;
1420   TREE_STATIC (decl) = 1;
1421   TREE_PUBLIC (decl) = 1;
1422 
1423   /* The decl has not been defined -- yet.  */
1424   DECL_EXTERNAL (decl) = 1;
1425 
1426   return decl;
1427 }
1428 
1429 /* Add local variable VAR into the current function body.  */
1430 
1431 void
1432 declare_local_var (VarDeclaration *var)
1433 {
1434   gcc_assert (!var->isDataseg () && !var->isMember ());
1435   gcc_assert (current_function_decl != NULL_TREE);
1436 
1437   FuncDeclaration *fd = cfun->language->function;
1438   tree decl = get_symbol_decl (var);
1439 
1440   gcc_assert (!TREE_STATIC (decl));
1441   d_pushdecl (decl);
1442   DECL_CONTEXT (decl) = current_function_decl;
1443 
1444   /* Compiler generated symbols.  */
1445   if (var == fd->vresult || var == fd->v_argptr)
1446     DECL_ARTIFICIAL (decl) = 1;
1447 
1448   if (DECL_LANG_FRAME_FIELD (decl))
1449     {
1450       /* Fixes debugging local variables.  */
1451       SET_DECL_VALUE_EXPR (decl, get_decl_tree (var));
1452       DECL_HAS_VALUE_EXPR_P (decl) = 1;
1453     }
1454 }
1455 
1456 /* Return an unnamed local temporary of type TYPE.  */
1457 
1458 tree
1459 build_local_temp (tree type)
1460 {
1461   tree decl = build_decl (input_location, VAR_DECL, NULL_TREE, type);
1462 
1463   DECL_CONTEXT (decl) = current_function_decl;
1464   DECL_ARTIFICIAL (decl) = 1;
1465   DECL_IGNORED_P (decl) = 1;
1466   d_pushdecl (decl);
1467 
1468   return decl;
1469 }
1470 
1471 /* Return the correct decl to be used for DECL.  For VAR_DECLs, this could
1472    instead be a FIELD_DECL from a closure, or a RESULT_DECL from a named return
1473    value.  For PARM_DECLs, this could be a FIELD_DECL for a non-local `this'.
1474    For all other kinds of decls, this just returns the result of
1475    get_symbol_decl().  */
1476 
1477 tree
1478 get_decl_tree (Declaration *decl)
1479 {
1480   tree t = get_symbol_decl (decl);
1481   FuncDeclaration *fd = cfun ? cfun->language->function : NULL;
1482   VarDeclaration *vd = decl->isVarDeclaration ();
1483 
1484   /* If cfun is NULL, then this is a global static.  */
1485   if (vd == NULL || fd == NULL)
1486     return t;
1487 
1488   /* Get the named return value.  */
1489   if (DECL_LANG_NRVO (t))
1490     return DECL_LANG_NRVO (t);
1491 
1492   /* Get the closure holding the var decl.  */
1493   if (DECL_LANG_FRAME_FIELD (t))
1494     {
1495       FuncDeclaration *parent = vd->toParent2 ()->isFuncDeclaration ();
1496       tree frame_ref = get_framedecl (fd, parent);
1497 
1498       return component_ref (build_deref (frame_ref),
1499 			    DECL_LANG_FRAME_FIELD (t));
1500     }
1501 
1502   /* Get the non-local 'this' value by going through parent link
1503      of nested classes, this routine pretty much undoes what
1504      getRightThis in the frontend removes from codegen.  */
1505   if (vd->parent != fd && vd->isThisDeclaration ())
1506     {
1507       /* Find the first parent that is a member function.  */
1508       while (!fd->isMember2 ())
1509 	{
1510 	  gcc_assert (fd->vthis);
1511 	  fd = fd->toParent2 ()->isFuncDeclaration ();
1512 	  gcc_assert (fd != NULL);
1513 	}
1514 
1515       AggregateDeclaration *ad = fd->isThis ();
1516       gcc_assert (ad != NULL);
1517 
1518       /* The parent function is for the same `this' declaration we are
1519 	 building a chain to.  Non-local declaration is inaccessible.  */
1520       if (fd->vthis == vd)
1521 	return error_no_frame_access (fd);
1522 
1523       t = get_decl_tree (fd->vthis);
1524       Dsymbol *outer = fd;
1525 
1526       while (outer != vd->parent)
1527 	{
1528 	  gcc_assert (ad != NULL);
1529 	  outer = ad->toParent2 ();
1530 
1531 	  /* Get the this->this parent link.  */
1532 	  tree vfield = get_symbol_decl (ad->vthis);
1533 	  t = component_ref (build_deref (t), vfield);
1534 
1535 	  ad = outer->isAggregateDeclaration ();
1536 	  if (ad != NULL)
1537 	    continue;
1538 
1539 	  fd = outer->isFuncDeclaration ();
1540 	  while (fd != NULL)
1541 	    {
1542 	      /* If outer function creates a closure, then the 'this'
1543 		 value would be the closure pointer, and the real
1544 		 'this' the first field of that closure.  */
1545 	      tree ff = get_frameinfo (fd);
1546 	      if (FRAMEINFO_CREATES_FRAME (ff))
1547 		{
1548 		  t = build_nop (build_pointer_type (FRAMEINFO_TYPE (ff)), t);
1549 		  t = indirect_ref (build_ctype (fd->vthis->type), t);
1550 		}
1551 
1552 	      if (fd == vd->parent)
1553 		break;
1554 
1555 	      /* Continue looking for the right `this'.  */
1556 	      outer = outer->toParent2 ();
1557 	      fd = outer->isFuncDeclaration ();
1558 	    }
1559 
1560 	  ad = outer->isAggregateDeclaration ();
1561 	}
1562 
1563       return t;
1564     }
1565 
1566   /* Auto variable that the back end will handle for us.  */
1567   return t;
1568 }
1569 
1570 /* Finish up a variable declaration and compile it all the way to
1571    the assembler language output.  */
1572 
1573 void
1574 d_finish_decl (tree decl)
1575 {
1576   gcc_assert (!error_operand_p (decl));
1577 
1578   /* We are sending this symbol to object file, can't be extern.  */
1579   TREE_STATIC (decl) = 1;
1580   DECL_EXTERNAL (decl) = 0;
1581 
1582   /* Update the TLS model as the linkage has been modified.  */
1583   if (DECL_THREAD_LOCAL_P (decl))
1584     set_decl_tls_model (decl, decl_default_tls_model (decl));
1585 
1586   relayout_decl (decl);
1587 
1588   if (flag_checking && DECL_INITIAL (decl))
1589     {
1590       /* Initializer must never be bigger than symbol size.  */
1591       HOST_WIDE_INT tsize = int_size_in_bytes (TREE_TYPE (decl));
1592       HOST_WIDE_INT dtsize =
1593 	int_size_in_bytes (TREE_TYPE (DECL_INITIAL (decl)));
1594 
1595       if (tsize < dtsize)
1596 	{
1597 	  tree name = DECL_ASSEMBLER_NAME (decl);
1598 
1599 	  internal_error ("Mismatch between declaration %qE size (%wd) and "
1600 			  "its initializer size (%wd).",
1601 			  IDENTIFIER_PRETTY_NAME (name)
1602 			  ? IDENTIFIER_PRETTY_NAME (name) : name,
1603 			  tsize, dtsize);
1604 	}
1605     }
1606 
1607   /* Without weak symbols, symbol should be put in .common, but that can't
1608      be done if there is a nonzero initializer.  */
1609   if (DECL_COMDAT (decl) && DECL_COMMON (decl)
1610       && initializer_zerop (DECL_INITIAL (decl)))
1611     DECL_INITIAL (decl) = error_mark_node;
1612 
1613   /* Add this decl to the current binding level.  */
1614   d_pushdecl (decl);
1615 
1616   rest_of_decl_compilation (decl, 1, 0);
1617 }
1618 
1619 /* Thunk code is based on g++.  */
1620 
1621 static int thunk_labelno;
1622 
1623 /* Create a static alias to function.  */
1624 
1625 static tree
1626 make_alias_for_thunk (tree function)
1627 {
1628   tree alias;
1629   char buf[256];
1630 
1631   /* Thunks may reference extern functions which cannot be aliased.  */
1632   if (DECL_EXTERNAL (function))
1633     return function;
1634 
1635   targetm.asm_out.generate_internal_label (buf, "LTHUNK", thunk_labelno);
1636   thunk_labelno++;
1637 
1638   alias = build_decl (DECL_SOURCE_LOCATION (function), FUNCTION_DECL,
1639 		      get_identifier (buf), TREE_TYPE (function));
1640   DECL_LANG_SPECIFIC (alias) = DECL_LANG_SPECIFIC (function);
1641   lang_hooks.dup_lang_specific_decl (alias);
1642   DECL_CONTEXT (alias) = NULL_TREE;
1643   TREE_READONLY (alias) = TREE_READONLY (function);
1644   TREE_THIS_VOLATILE (alias) = TREE_THIS_VOLATILE (function);
1645   TREE_PUBLIC (alias) = 0;
1646 
1647   DECL_EXTERNAL (alias) = 0;
1648   DECL_ARTIFICIAL (alias) = 1;
1649 
1650   DECL_DECLARED_INLINE_P (alias) = 0;
1651   DECL_INITIAL (alias) = error_mark_node;
1652   DECL_ARGUMENTS (alias) = copy_list (DECL_ARGUMENTS (function));
1653 
1654   TREE_ADDRESSABLE (alias) = 1;
1655   TREE_USED (alias) = 1;
1656   SET_DECL_ASSEMBLER_NAME (alias, DECL_NAME (alias));
1657 
1658   if (!flag_syntax_only)
1659     {
1660       cgraph_node *aliasn;
1661       aliasn = cgraph_node::create_same_body_alias (alias, function);
1662       gcc_assert (aliasn != NULL);
1663     }
1664   return alias;
1665 }
1666 
1667 /* Emit the definition of a D vtable thunk.  */
1668 
1669 static void
1670 finish_thunk (tree thunk, tree function)
1671 {
1672   /* Setup how D thunks are outputted.  */
1673   int fixed_offset = -THUNK_LANG_OFFSET (thunk);
1674   bool this_adjusting = true;
1675   tree alias;
1676 
1677   if (TARGET_USE_LOCAL_THUNK_ALIAS_P (function))
1678     alias = make_alias_for_thunk (function);
1679   else
1680     alias = function;
1681 
1682   TREE_ADDRESSABLE (function) = 1;
1683   TREE_USED (function) = 1;
1684 
1685   if (flag_syntax_only)
1686     {
1687       TREE_ASM_WRITTEN (thunk) = 1;
1688       return;
1689     }
1690 
1691   if (TARGET_USE_LOCAL_THUNK_ALIAS_P (function)
1692       && targetm_common.have_named_sections)
1693     {
1694       tree fn = function;
1695       symtab_node *symbol = symtab_node::get (function);
1696 
1697       if (symbol != NULL && symbol->alias)
1698 	{
1699 	  if (symbol->analyzed)
1700 	    fn = symtab_node::get (function)->ultimate_alias_target ()->decl;
1701 	  else
1702 	    fn = symtab_node::get (function)->alias_target;
1703 	}
1704       resolve_unique_section (fn, 0, flag_function_sections);
1705 
1706       if (DECL_SECTION_NAME (fn) != NULL && DECL_ONE_ONLY (fn))
1707 	{
1708 	  resolve_unique_section (thunk, 0, flag_function_sections);
1709 
1710 	  /* Output the thunk into the same section as function.  */
1711 	  set_decl_section_name (thunk, DECL_SECTION_NAME (fn));
1712 	  symtab_node::get (thunk)->implicit_section
1713 	    = symtab_node::get (fn)->implicit_section;
1714 	}
1715     }
1716 
1717   /* Set up cloned argument trees for the thunk.  */
1718   tree t = NULL_TREE;
1719   for (tree a = DECL_ARGUMENTS (function); a; a = DECL_CHAIN (a))
1720     {
1721       tree x = copy_node (a);
1722       DECL_CHAIN (x) = t;
1723       DECL_CONTEXT (x) = thunk;
1724       SET_DECL_RTL (x, NULL);
1725       DECL_HAS_VALUE_EXPR_P (x) = 0;
1726       TREE_ADDRESSABLE (x) = 0;
1727       t = x;
1728     }
1729   DECL_ARGUMENTS (thunk) = nreverse (t);
1730   TREE_ASM_WRITTEN (thunk) = 1;
1731 
1732   cgraph_node *funcn, *thunk_node;
1733 
1734   funcn = cgraph_node::get_create (function);
1735   gcc_assert (funcn);
1736   thunk_node = funcn->create_thunk (thunk, thunk, this_adjusting,
1737 				    fixed_offset, 0, 0, 0, alias);
1738 
1739   if (DECL_ONE_ONLY (function))
1740     thunk_node->add_to_same_comdat_group (funcn);
1741 
1742   /* Target assemble_mi_thunk doesn't work across section boundaries
1743      on many targets, instead force thunk to be expanded in gimple.  */
1744   if (DECL_EXTERNAL (function))
1745     {
1746       /* cgraph::expand_thunk writes over current_function_decl, so if this
1747 	 could ever be in use by the codegen pass, we want to know about it.  */
1748       gcc_assert (current_function_decl == NULL_TREE);
1749 
1750       if (!stdarg_p (TREE_TYPE (thunk)))
1751 	{
1752 	  thunk_node->create_edge (funcn, NULL, thunk_node->count);
1753 	  thunk_node->expand_thunk (false, true);
1754 	}
1755 
1756       /* Tell the back-end to not bother inlining the function, this is
1757 	 assumed not to work as it could be referencing symbols outside
1758 	 of the current compilation unit.  */
1759       DECL_UNINLINABLE (function) = 1;
1760     }
1761 }
1762 
1763 /* Return a thunk to DECL.  Thunks adjust the incoming `this' pointer by OFFSET.
1764    Adjustor thunks are created and pointers to them stored in the method entries
1765    in the vtable in order to set the this pointer to the start of the object
1766    instance corresponding to the implementing method.  */
1767 
1768 tree
1769 make_thunk (FuncDeclaration *decl, int offset)
1770 {
1771   tree function = get_symbol_decl (decl);
1772 
1773   if (!DECL_ARGUMENTS (function) || !DECL_RESULT (function))
1774     {
1775       /* Compile the function body before generating the thunk, this is done
1776 	 even if the decl is external to the current module.  */
1777       if (decl->fbody)
1778 	build_decl_tree (decl);
1779       else
1780 	{
1781 	  /* Build parameters for functions that are not being compiled,
1782 	     so that they can be correctly cloned in finish_thunk.  */
1783 	  tree fntype = TREE_TYPE (function);
1784 	  tree params = NULL_TREE;
1785 
1786 	  for (tree t = TYPE_ARG_TYPES (fntype); t; t = TREE_CHAIN (t))
1787 	    {
1788 	      if (t == void_list_node)
1789 		break;
1790 
1791 	      tree param = build_decl (DECL_SOURCE_LOCATION (function),
1792 				       PARM_DECL, NULL_TREE, TREE_VALUE (t));
1793 	      DECL_ARG_TYPE (param) = TREE_TYPE (param);
1794 	      DECL_ARTIFICIAL (param) = 1;
1795 	      DECL_IGNORED_P (param) = 1;
1796 	      DECL_CONTEXT (param) = function;
1797 	      params = chainon (params, param);
1798 	    }
1799 
1800 	  DECL_ARGUMENTS (function) = params;
1801 
1802 	  /* Also build the result decl, which is needed when force creating
1803 	     the thunk in gimple inside cgraph_node::expand_thunk.  */
1804 	  tree resdecl = build_decl (DECL_SOURCE_LOCATION (function),
1805 				     RESULT_DECL, NULL_TREE,
1806 				     TREE_TYPE (fntype));
1807 	  DECL_ARTIFICIAL (resdecl) = 1;
1808 	  DECL_IGNORED_P (resdecl) = 1;
1809 	  DECL_CONTEXT (resdecl) = function;
1810 	  DECL_RESULT (function) = resdecl;
1811 	}
1812     }
1813 
1814   /* Don't build the thunk if the compilation step failed.  */
1815   if (global.errors)
1816     return error_mark_node;
1817 
1818   /* See if we already have the thunk in question.  */
1819   for (tree t = DECL_LANG_THUNKS (function); t; t = DECL_CHAIN (t))
1820     {
1821       if (THUNK_LANG_OFFSET (t) == offset)
1822 	return t;
1823     }
1824 
1825   tree thunk = build_decl (DECL_SOURCE_LOCATION (function),
1826 			   FUNCTION_DECL, NULL_TREE, TREE_TYPE (function));
1827   DECL_LANG_SPECIFIC (thunk) = DECL_LANG_SPECIFIC (function);
1828   lang_hooks.dup_lang_specific_decl (thunk);
1829   THUNK_LANG_OFFSET (thunk) = offset;
1830 
1831   TREE_READONLY (thunk) = TREE_READONLY (function);
1832   TREE_THIS_VOLATILE (thunk) = TREE_THIS_VOLATILE (function);
1833   TREE_NOTHROW (thunk) = TREE_NOTHROW (function);
1834 
1835   DECL_CONTEXT (thunk) = d_decl_context (decl);
1836 
1837   /* Thunks inherit the public access of the function they are targetting.
1838      When the function is outside the current compilation unit however, then the
1839      thunk must be kept private to not conflict.  */
1840   TREE_PUBLIC (thunk) = TREE_PUBLIC (function) && !DECL_EXTERNAL (function);
1841 
1842   DECL_EXTERNAL (thunk) = 0;
1843 
1844   /* Thunks are always addressable.  */
1845   TREE_ADDRESSABLE (thunk) = 1;
1846   TREE_USED (thunk) = 1;
1847   DECL_ARTIFICIAL (thunk) = 1;
1848   DECL_DECLARED_INLINE_P (thunk) = 0;
1849 
1850   DECL_VISIBILITY (thunk) = DECL_VISIBILITY (function);
1851   DECL_COMDAT (thunk) = DECL_COMDAT (function);
1852   DECL_WEAK (thunk) = DECL_WEAK (function);
1853 
1854   tree target_name = DECL_ASSEMBLER_NAME (function);
1855   unsigned identlen = IDENTIFIER_LENGTH (target_name) + 14;
1856   const char *ident = XNEWVEC (const char, identlen);
1857   snprintf (CONST_CAST (char *, ident), identlen,
1858 	    "_DT%u%s", offset, IDENTIFIER_POINTER (target_name));
1859 
1860   DECL_NAME (thunk) = get_identifier (ident);
1861   SET_DECL_ASSEMBLER_NAME (thunk, DECL_NAME (thunk));
1862 
1863   d_keep (thunk);
1864 
1865   finish_thunk (thunk, function);
1866 
1867   /* Add it to the list of thunks associated with the function.  */
1868   DECL_LANG_THUNKS (thunk) = NULL_TREE;
1869   DECL_CHAIN (thunk) = DECL_LANG_THUNKS (function);
1870   DECL_LANG_THUNKS (function) = thunk;
1871 
1872   return thunk;
1873 }
1874 
1875 /* Create the FUNCTION_DECL for a function definition.
1876    This function creates a binding context for the function body
1877    as well as setting up the FUNCTION_DECL in current_function_decl.
1878    Returns the previous function context if it was already set.  */
1879 
1880 tree
1881 start_function (FuncDeclaration *fd)
1882 {
1883   tree fndecl = get_symbol_decl (fd);
1884 
1885   /* Function has been defined, check now whether we intend to send it to
1886      object file, or it really is extern.  Such as inlinable functions from
1887      modules not in this compilation, or thunk aliases.  */
1888   TemplateInstance *ti = fd->isInstantiated ();
1889   if (ti && ti->needsCodegen ())
1890     {
1891       /* Warn about templates instantiated in this compilation.  */
1892       if (ti == fd->parent)
1893 	{
1894 	  warning (OPT_Wtemplates, "%s %qs instantiated",
1895 		   ti->kind (), ti->toPrettyChars (false));
1896 	}
1897 
1898       DECL_EXTERNAL (fndecl) = 0;
1899     }
1900   else
1901     {
1902       Module *md = fd->getModule ();
1903       if (md && md->isRoot ())
1904 	DECL_EXTERNAL (fndecl) = 0;
1905     }
1906 
1907   DECL_INITIAL (fndecl) = error_mark_node;
1908 
1909   /* Add this decl to the current binding level.  */
1910   d_pushdecl (fndecl);
1911 
1912   /* Save the current function context.  */
1913   tree old_context = current_function_decl;
1914 
1915   if (old_context)
1916     push_function_context ();
1917 
1918   /* Let GCC know the current scope is this function.  */
1919   current_function_decl = fndecl;
1920 
1921   tree restype = TREE_TYPE (TREE_TYPE (fndecl));
1922   tree resdecl = build_decl (make_location_t (fd->loc), RESULT_DECL,
1923 			     NULL_TREE, restype);
1924 
1925   DECL_RESULT (fndecl) = resdecl;
1926   DECL_CONTEXT (resdecl) = fndecl;
1927   DECL_ARTIFICIAL (resdecl) = 1;
1928   DECL_IGNORED_P (resdecl) = 1;
1929 
1930   /* Initialize the RTL code for the function.  */
1931   allocate_struct_function (fndecl, false);
1932 
1933   /* Store the end of the function.  */
1934   if (fd->endloc.filename)
1935     cfun->function_end_locus = make_location_t (fd->endloc);
1936   else
1937     cfun->function_end_locus = DECL_SOURCE_LOCATION (fndecl);
1938 
1939   cfun->language = ggc_cleared_alloc<language_function> ();
1940   cfun->language->function = fd;
1941 
1942   /* Default chain value is 'null' unless parent found.  */
1943   cfun->language->static_chain = null_pointer_node;
1944 
1945   /* Find module for this function.  */
1946   for (Dsymbol *p = fd->parent; p != NULL; p = p->parent)
1947     {
1948       cfun->language->module = p->isModule ();
1949       if (cfun->language->module)
1950 	break;
1951     }
1952   gcc_assert (cfun->language->module != NULL);
1953 
1954   /* Begin the statement tree for this function.  */
1955   push_stmt_list ();
1956   push_binding_level (level_function);
1957 
1958   return old_context;
1959 }
1960 
1961 /* Finish up a function declaration and compile that function all
1962    the way to assembler language output.  The free the storage for
1963    the function definition.  Restores the previous function context.  */
1964 
1965 void
1966 finish_function (tree old_context)
1967 {
1968   tree fndecl = current_function_decl;
1969 
1970   /* Tie off the statement tree for this function.  */
1971   tree block = pop_binding_level ();
1972   tree body = pop_stmt_list ();
1973   tree bind = build3 (BIND_EXPR, void_type_node,
1974 		      BLOCK_VARS (block), body, block);
1975 
1976   gcc_assert (vec_safe_is_empty (d_function_chain->stmt_list));
1977 
1978   /* Back-end expects a statement list to come from somewhere, however
1979      pop_stmt_list returns expressions when there is a single statement.
1980      So here we create a statement list unconditionally.  */
1981   if (TREE_CODE (body) != STATEMENT_LIST)
1982     {
1983       tree stmtlist = alloc_stmt_list ();
1984       append_to_statement_list_force (body, &stmtlist);
1985       BIND_EXPR_BODY (bind) = stmtlist;
1986     }
1987   else if (!STATEMENT_LIST_HEAD (body))
1988     {
1989       /* For empty functions add a void return.  */
1990       append_to_statement_list_force (return_expr (NULL_TREE), &body);
1991     }
1992 
1993   DECL_SAVED_TREE (fndecl) = bind;
1994 
1995   if (!errorcount && !global.errors)
1996     {
1997       /* Dump the D-specific tree IR.  */
1998       dump_function (TDI_original, fndecl);
1999 
2000       cgraph_node::finalize_function (fndecl, true);
2001     }
2002 
2003   /* We're leaving the context of this function, so free it.  */
2004   ggc_free (cfun->language);
2005   cfun->language = NULL;
2006   set_cfun (NULL);
2007 
2008   if (old_context)
2009     pop_function_context ();
2010 
2011   current_function_decl = old_context;
2012 }
2013 
2014 /* Mark DECL, which is a VAR_DECL or FUNCTION_DECL as a symbol that
2015    must be emitted in this, output module.  */
2016 
2017 void
2018 mark_needed (tree decl)
2019 {
2020   TREE_USED (decl) = 1;
2021 
2022   if (TREE_CODE (decl) == FUNCTION_DECL)
2023     {
2024       struct cgraph_node *node = cgraph_node::get_create (decl);
2025       node->forced_by_abi = true;
2026     }
2027   else if (VAR_P (decl))
2028     {
2029       struct varpool_node *node = varpool_node::get_create (decl);
2030       node->forced_by_abi = true;
2031     }
2032 }
2033 
2034 /* Get the offset to the BC's vtbl[] initializer from the start of CD.
2035    Returns "~0u" if the base class is not found in any vtable interfaces.  */
2036 
2037 unsigned
2038 base_vtable_offset (ClassDeclaration *cd, BaseClass *bc)
2039 {
2040   unsigned csymoffset = Target::classinfosize;
2041   unsigned interfacesize = int_size_in_bytes (vtbl_interface_type_node);
2042   csymoffset += cd->vtblInterfaces->dim * interfacesize;
2043 
2044   for (size_t i = 0; i < cd->vtblInterfaces->dim; i++)
2045     {
2046       BaseClass *b = (*cd->vtblInterfaces)[i];
2047       if (b == bc)
2048 	return csymoffset;
2049       csymoffset += b->sym->vtbl.dim * Target::ptrsize;
2050     }
2051 
2052   /* Check all overriding interface vtbl[]s.  */
2053   for (ClassDeclaration *cd2 = cd->baseClass; cd2; cd2 = cd2->baseClass)
2054     {
2055       for (size_t k = 0; k < cd2->vtblInterfaces->dim; k++)
2056 	{
2057 	  BaseClass *bs = (*cd2->vtblInterfaces)[k];
2058 	  if (bs->fillVtbl (cd, NULL, 0))
2059 	    {
2060 	      if (bc == bs)
2061 		return csymoffset;
2062 	      csymoffset += bs->sym->vtbl.dim * Target::ptrsize;
2063 	    }
2064 	}
2065     }
2066 
2067   return ~0u;
2068 }
2069 
2070 /* Get the VAR_DECL of the vtable symbol for DECL.  If this does not yet exist,
2071    create it.  The vtable is accessible via ClassInfo, but since it is needed
2072    frequently (like for rtti comparisons), make it directly accessible.  */
2073 
2074 tree
2075 get_vtable_decl (ClassDeclaration *decl)
2076 {
2077   if (decl->vtblsym)
2078     return decl->vtblsym;
2079 
2080   tree ident = mangle_internal_decl (decl, "__vtbl", "Z");
2081   /* Note: Using a static array type for the VAR_DECL, the DECL_INITIAL value
2082      will have a different type.  However the back-end seems to accept this.  */
2083   tree type = build_ctype (Type::tvoidptr->sarrayOf (decl->vtbl.dim));
2084 
2085   decl->vtblsym = declare_extern_var (ident, type);
2086   DECL_LANG_SPECIFIC (decl->vtblsym) = build_lang_decl (NULL);
2087 
2088   /* Class is a reference, want the record type.  */
2089   DECL_CONTEXT (decl->vtblsym) = TREE_TYPE (build_ctype (decl->type));
2090   TREE_READONLY (decl->vtblsym) = 1;
2091   DECL_VIRTUAL_P (decl->vtblsym) = 1;
2092 
2093   SET_DECL_ALIGN (decl->vtblsym, TARGET_VTABLE_ENTRY_ALIGN);
2094   DECL_USER_ALIGN (decl->vtblsym) = true;
2095 
2096   return decl->vtblsym;
2097 }
2098 
2099 /* Helper function of build_class_instance.  Find the field inside aggregate
2100    TYPE identified by IDENT at field OFFSET.  */
2101 
2102 static tree
2103 find_aggregate_field (tree type, tree ident, tree offset)
2104 {
2105   tree fields = TYPE_FIELDS (type);
2106 
2107   for (tree field = fields; field != NULL_TREE; field = TREE_CHAIN (field))
2108     {
2109       if (DECL_NAME (field) == NULL_TREE
2110 	  && RECORD_OR_UNION_TYPE_P (TREE_TYPE (field))
2111 	  && ANON_AGGR_TYPE_P (TREE_TYPE (field)))
2112 	{
2113 	  /* Search nesting anonymous structs and unions.  */
2114 	  tree vfield = find_aggregate_field (TREE_TYPE (field),
2115 					      ident, offset);
2116 	  if (vfield != NULL_TREE)
2117 	    return vfield;
2118 	}
2119       else if (DECL_NAME (field) == ident
2120 	       && (offset == NULL_TREE
2121 		   || DECL_FIELD_OFFSET (field) == offset))
2122 	{
2123 	  /* Found matching field at offset.  */
2124 	  return field;
2125 	}
2126     }
2127 
2128   return NULL_TREE;
2129 }
2130 
2131 /* Helper function of build_new_class_expr.  Return a constructor that matches
2132    the layout of the class expression EXP.  */
2133 
2134 static tree
2135 build_class_instance (ClassReferenceExp *exp)
2136 {
2137   ClassDeclaration *cd = exp->originalClass ();
2138   tree type = TREE_TYPE (build_ctype (exp->value->stype));
2139   vec<constructor_elt, va_gc> *ve = NULL;
2140 
2141   /* The set base vtable field.  */
2142   tree vptr = build_address (get_vtable_decl (cd));
2143   CONSTRUCTOR_APPEND_ELT (ve, TYPE_FIELDS (type), vptr);
2144 
2145   /* Go through the inheritance graph from top to bottom.  This will add all
2146      values to the constructor out of order, however build_struct_literal
2147      will re-order all values before returning the finished literal.  */
2148   for (ClassDeclaration *bcd = cd; bcd != NULL; bcd = bcd->baseClass)
2149     {
2150       /* Anonymous vtable interface fields are laid out before the fields of
2151 	 each class.  The interface offset is used to determine where to put
2152 	 the classinfo offset reference.  */
2153       for (size_t i = 0; i < bcd->vtblInterfaces->dim; i++)
2154 	{
2155 	  BaseClass *bc = (*bcd->vtblInterfaces)[i];
2156 
2157 	  for (ClassDeclaration *cd2 = cd; 1; cd2 = cd2->baseClass)
2158 	    {
2159 	      gcc_assert (cd2 != NULL);
2160 
2161 	      unsigned csymoffset = base_vtable_offset (cd2, bc);
2162 	      /* If the base class vtable was found.  */
2163 	      if (csymoffset != ~0u)
2164 		{
2165 		  tree csym = build_address (get_classinfo_decl (cd2));
2166 		  csym = build_offset (csym, size_int (csymoffset));
2167 
2168 		  tree field = find_aggregate_field (type, NULL_TREE,
2169 						     size_int (bc->offset));
2170 		  gcc_assert (field != NULL_TREE);
2171 
2172 		  CONSTRUCTOR_APPEND_ELT (ve, field, csym);
2173 		  break;
2174 		}
2175 	    }
2176 	}
2177 
2178       /* Generate initial values of all fields owned by current class.
2179 	 Use both the name and offset to find the right field.  */
2180       for (size_t i = 0; i < bcd->fields.dim; i++)
2181 	{
2182 	  VarDeclaration *vfield = bcd->fields[i];
2183 	  int index = exp->findFieldIndexByName (vfield);
2184 	  gcc_assert (index != -1);
2185 
2186 	  Expression *value = (*exp->value->elements)[index];
2187 	  if (!value)
2188 	    continue;
2189 
2190 	  /* Use find_aggregate_field to get the overridden field decl,
2191 	     instead of the field associated with the base class.  */
2192 	  tree field = get_symbol_decl (bcd->fields[i]);
2193 	  field = find_aggregate_field (type, DECL_NAME (field),
2194 					DECL_FIELD_OFFSET (field));
2195 	  gcc_assert (field != NULL_TREE);
2196 
2197 	  CONSTRUCTOR_APPEND_ELT (ve, field, build_expr (value, true));
2198 	}
2199     }
2200 
2201   return build_struct_literal (type, ve);
2202 }
2203 
2204 /* Get the VAR_DECL of a class instance representing EXPR as static data.
2205    If this does not yet exist, create it.  This is used to support initializing
2206    a static variable that is of a class type using values known during CTFE.
2207    In user code, it is analogous to the following code snippet.
2208 
2209     enum E = new C(1, 2, 3);
2210 
2211    That we write the contents of `C(1, 2, 3)' to static data is only a compiler
2212    implementation detail.  The initialization of these symbols could be done at
2213    run-time using during as part of the module initialization or shared static
2214    constructors phase of run-time start-up - whichever comes after `gc_init()'.
2215    And infact that would be the better thing to do here eventually.  */
2216 
2217 tree
2218 build_new_class_expr (ClassReferenceExp *expr)
2219 {
2220   if (expr->value->sym)
2221     return expr->value->sym;
2222 
2223   /* Build the reference symbol.  */
2224   tree type = build_ctype (expr->value->stype);
2225   expr->value->sym = build_artificial_decl (TREE_TYPE (type), NULL_TREE, "C");
2226 
2227   DECL_INITIAL (expr->value->sym) = build_class_instance (expr);
2228   d_pushdecl (expr->value->sym);
2229   rest_of_decl_compilation (expr->value->sym, 1, 0);
2230 
2231   return expr->value->sym;
2232 }
2233 
2234 /* Get the VAR_DECL of the static initializer symbol for the struct/class DECL.
2235    If this does not yet exist, create it.  The static initializer data is
2236    accessible via TypeInfo, and is also used in 'new class' and default
2237    initializing struct literals.  */
2238 
2239 tree
2240 aggregate_initializer_decl (AggregateDeclaration *decl)
2241 {
2242   if (decl->sinit)
2243     return decl->sinit;
2244 
2245   /* Class is a reference, want the record type.  */
2246   tree type = build_ctype (decl->type);
2247   StructDeclaration *sd = decl->isStructDeclaration ();
2248   if (!sd)
2249     type = TREE_TYPE (type);
2250 
2251   tree ident = mangle_internal_decl (decl, "__init", "Z");
2252 
2253   decl->sinit = declare_extern_var (ident, type);
2254   DECL_LANG_SPECIFIC (decl->sinit) = build_lang_decl (NULL);
2255 
2256   DECL_CONTEXT (decl->sinit) = type;
2257   TREE_READONLY (decl->sinit) = 1;
2258 
2259   /* Honor struct alignment set by user.  */
2260   if (sd && sd->alignment != STRUCTALIGN_DEFAULT)
2261     {
2262       SET_DECL_ALIGN (decl->sinit, sd->alignment * BITS_PER_UNIT);
2263       DECL_USER_ALIGN (decl->sinit) = true;
2264     }
2265 
2266   return decl->sinit;
2267 }
2268 
2269 /* Generate the data for the static initializer.  */
2270 
2271 tree
2272 layout_class_initializer (ClassDeclaration *cd)
2273 {
2274   NewExp *ne = NewExp::create (cd->loc, NULL, NULL, cd->type, NULL);
2275   ne->type = cd->type;
2276 
2277   Expression *e = ne->ctfeInterpret ();
2278   gcc_assert (e->op == TOKclassreference);
2279 
2280   return build_class_instance ((ClassReferenceExp *) e);
2281 }
2282 
2283 tree
2284 layout_struct_initializer (StructDeclaration *sd)
2285 {
2286   StructLiteralExp *sle = StructLiteralExp::create (sd->loc, sd, NULL);
2287 
2288   if (!sd->fill (sd->loc, sle->elements, true))
2289     gcc_unreachable ();
2290 
2291   sle->type = sd->type;
2292   return build_expr (sle, true);
2293 }
2294 
2295 /* Get the VAR_DECL of the static initializer symbol for the enum DECL.
2296    If this does not yet exist, create it.  The static initializer data is
2297    accessible via TypeInfo_Enum, but the field member type is a byte[] that
2298    requires a pointer to a symbol reference.  */
2299 
2300 tree
2301 enum_initializer_decl (EnumDeclaration *decl)
2302 {
2303   if (decl->sinit)
2304     return decl->sinit;
2305 
2306   tree type = build_ctype (decl->type);
2307 
2308   Identifier *ident_save = decl->ident;
2309   if (!decl->ident)
2310     decl->ident = Identifier::generateId ("__enum");
2311   tree ident = mangle_internal_decl (decl, "__init", "Z");
2312   decl->ident = ident_save;
2313 
2314   decl->sinit = declare_extern_var (ident, type);
2315   DECL_LANG_SPECIFIC (decl->sinit) = build_lang_decl (NULL);
2316 
2317   DECL_CONTEXT (decl->sinit) = d_decl_context (decl);
2318   TREE_READONLY (decl->sinit) = 1;
2319 
2320   return decl->sinit;
2321 }
2322 
2323 /* Return an anonymous static variable of type TYPE, initialized with INIT,
2324    and optionally prefixing the name with PREFIX.  */
2325 
2326 tree
2327 build_artificial_decl (tree type, tree init, const char *prefix)
2328 {
2329   tree decl = build_decl (UNKNOWN_LOCATION, VAR_DECL, NULL_TREE, type);
2330   const char *name = prefix ? prefix : "___s";
2331   char *label;
2332 
2333   ASM_FORMAT_PRIVATE_NAME (label, name, DECL_UID (decl));
2334   SET_DECL_ASSEMBLER_NAME (decl, get_identifier (label));
2335   DECL_NAME (decl) = DECL_ASSEMBLER_NAME (decl);
2336 
2337   TREE_PUBLIC (decl) = 0;
2338   TREE_STATIC (decl) = 1;
2339   TREE_USED (decl) = 1;
2340   DECL_IGNORED_P (decl) = 1;
2341   DECL_ARTIFICIAL (decl) = 1;
2342 
2343   /* Perhaps at some point the initializer constant should be hashed
2344      to remove duplicates.  */
2345   DECL_INITIAL (decl) = init;
2346 
2347   return decl;
2348 }
2349 
2350 /* Build TYPE_DECL for the declaration DSYM.  */
2351 
2352 void
2353 build_type_decl (tree type, Dsymbol *dsym)
2354 {
2355   if (TYPE_STUB_DECL (type))
2356     return;
2357 
2358   gcc_assert (!POINTER_TYPE_P (type));
2359 
2360   /* If a templated type, use the template instance name, as that includes all
2361      template parameters.  */
2362   const char *name = dsym->parent->isTemplateInstance ()
2363     ? ((TemplateInstance *) dsym->parent)->toChars () : dsym->ident->toChars ();
2364 
2365   tree decl = build_decl (make_location_t (dsym->loc), TYPE_DECL,
2366 			  get_identifier (name), type);
2367   SET_DECL_ASSEMBLER_NAME (decl, get_identifier (d_mangle_decl (dsym)));
2368   TREE_PUBLIC (decl) = 1;
2369   DECL_ARTIFICIAL (decl) = 1;
2370   DECL_CONTEXT (decl) = d_decl_context (dsym);
2371 
2372   TYPE_CONTEXT (type) = DECL_CONTEXT (decl);
2373   TYPE_NAME (type) = decl;
2374 
2375   /* Not sure if there is a need for separate TYPE_DECLs in
2376      TYPE_NAME and TYPE_STUB_DECL.  */
2377   if (TREE_CODE (type) == ENUMERAL_TYPE || RECORD_OR_UNION_TYPE_P (type))
2378     TYPE_STUB_DECL (type) = decl;
2379 
2380   rest_of_decl_compilation (decl, SCOPE_FILE_SCOPE_P (decl), 0);
2381 }
2382 
2383 /* Create a declaration for field NAME of a given TYPE, setting the flags
2384    for whether the field is ARTIFICIAL and/or IGNORED.  */
2385 
2386 tree
2387 create_field_decl (tree type, const char *name, int artificial, int ignored)
2388 {
2389   tree decl = build_decl (input_location, FIELD_DECL,
2390 			  name ? get_identifier (name) : NULL_TREE, type);
2391   DECL_ARTIFICIAL (decl) = artificial;
2392   DECL_IGNORED_P (decl) = ignored;
2393 
2394   return decl;
2395 }
2396 
2397 /* Return the COMDAT group into which DECL should be placed.  */
2398 
2399 static tree
2400 d_comdat_group (tree decl)
2401 {
2402   /* If already part of a comdat group, use that.  */
2403   if (DECL_COMDAT_GROUP (decl))
2404     return DECL_COMDAT_GROUP (decl);
2405 
2406   return DECL_ASSEMBLER_NAME (decl);
2407 }
2408 
2409 /* Set DECL up to have the closest approximation of "initialized common"
2410    linkage available.  */
2411 
2412 void
2413 d_comdat_linkage (tree decl)
2414 {
2415   if (flag_weak)
2416     make_decl_one_only (decl, d_comdat_group (decl));
2417   else if (TREE_CODE (decl) == FUNCTION_DECL
2418 	   || (VAR_P (decl) && DECL_ARTIFICIAL (decl)))
2419     /* We can just emit function and compiler-generated variables statically;
2420        having multiple copies is (for the most part) only a waste of space.  */
2421     TREE_PUBLIC (decl) = 0;
2422   else if (DECL_INITIAL (decl) == NULL_TREE
2423 	   || DECL_INITIAL (decl) == error_mark_node)
2424     /* Fallback, cannot have multiple copies.  */
2425     DECL_COMMON (decl) = 1;
2426 
2427   if (TREE_PUBLIC (decl))
2428     DECL_COMDAT (decl) = 1;
2429 }
2430 
2431 /* Set DECL up to have the closest approximation of "linkonce" linkage.  */
2432 
2433 void
2434 d_linkonce_linkage (tree decl)
2435 {
2436   /* Weak definitions have to be public.  */
2437   if (!TREE_PUBLIC (decl))
2438     return;
2439 
2440   /* Necessary to allow DECL_ONE_ONLY or DECL_WEAK functions to be inlined.  */
2441   if (TREE_CODE (decl) == FUNCTION_DECL)
2442     DECL_DECLARED_INLINE_P (decl) = 1;
2443 
2444   /* No weak support, fallback to COMDAT linkage.  */
2445   if (!flag_weak)
2446    return d_comdat_linkage (decl);
2447 
2448   make_decl_one_only (decl, d_comdat_group (decl));
2449 }
2450