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