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