Debian Codegraph @

gcc/d/d-lang.cc

raw
1 /* d-lang.cc -- Language-dependent hooks for D.
2 Copyright (C) 2006-2025 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/cond.h"
24 #include "dmd/declaration.h"
25 #include "dmd/doc.h"
26 #include "dmd/dsymbol.h"
27 #include "dmd/errors.h"
28 #include "dmd/expression.h"
29 #include "dmd/hdrgen.h"
30 #include "dmd/id.h"
31 #include "dmd/identifier.h"
32 #include "dmd/json.h"
33 #include "dmd/mangle.h"
34 #include "dmd/module.h"
35 #include "dmd/mtype.h"
36 #include "dmd/target.h"
37 #include "dmd/template.h"
38
39 #include "opts.h"
40 #include "alias.h"
41 #include "tree.h"
42 #include "diagnostic.h"
43 #include "fold-const.h"
44 #include "toplev.h"
45 #include "langhooks.h"
46 #include "langhooks-def.h"
47 #include "target.h"
48 #include "function.h"
49 #include "stringpool.h"
50 #include "stor-layout.h"
51 #include "varasm.h"
52 #include "output.h"
53 #include "print-tree.h"
54 #include "debug.h"
55 #include "input.h"
56
57 #include "d-tree.h"
58 #include "d-frontend.h"
59
60
61 /* Array of D frontend type/decl nodes. */
62 tree d_global_trees[DTI_MAX];
63
64 /* True if compilation is currently inside the D frontend semantic passes. */
65 bool doing_semantic_analysis_p = false;
66
67 /* Options handled by the compiler that are separate from the frontend. */
68 struct d_option_data
69 {
70 const char *fonly; /* -fonly=<arg> */
71 const char *multilib; /* -imultilib <dir> */
72 const char *prefix; /* -iprefix <dir> */
73
74 bool deps; /* -M */
75 bool deps_skip_system; /* -MM */
76 const char *deps_filename; /* -M[M]D */
77 const char *deps_filename_user; /* -MF <arg> */
78 vec <const char *> deps_target; /* -M[QT] <arg> */
79 bool deps_phony; /* -MP */
80
81 bool stdinc; /* -nostdinc */
82 }
83 d_option;
84
85 /* List of modules being compiled. */
86 static Modules builtin_modules;
87
88 /* The current and global binding level in effect. */
89 struct binding_level *current_binding_level;
90 struct binding_level *global_binding_level;
91
92 /* The context to be used for global declarations. */
93 static GTY(()) tree global_context;
94
95 /* Array of all global declarations to pass back to the middle-end. */
96 static GTY(()) vec <tree, va_gc> *global_declarations;
97
98 /* Support for GCC-style command-line make dependency generation.
99 Adds TARGET to the make dependencies target buffer.
100 QUOTED is true if the string should be quoted. */
101
102 static void
103 deps_add_target (const char *target, bool quoted)
104 {
105 obstack buffer;
106 gcc_obstack_init (&buffer);
107
108 if (!quoted)
109 {
110 obstack_grow0 (&buffer, target, strlen (target));
111 d_option.deps_target.safe_push ((const char *) obstack_finish (&buffer));
112 return;
113 }
114
115 /* Quote characters in target which are significant to Make. */
116 unsigned slashes = 0;
117
118 for (const char *p = target; *p != '\0'; p++)
119 {
120 switch (*p)
121 {
122 case '\\':
123 slashes++;
124 break;
125
126 case ' ':
127 case '\t':
128 while (slashes--)
129 obstack_1grow (&buffer, '\\');
130 obstack_1grow (&buffer, '\\');
131 goto Ldef;
132
133 case '$':
134 obstack_1grow (&buffer, '$');
135 goto Ldef;
136
137 case '#':
138 case ':':
139 obstack_1grow (&buffer, '\\');
140 goto Ldef;
141
142 default:
143 Ldef:
144 slashes = 0;
145 break;
146 }
147
148 obstack_1grow (&buffer, *p);
149 }
150
151 obstack_1grow (&buffer, '\0');
152 d_option.deps_target.safe_push ((const char *) obstack_finish (&buffer));
153 }
154
155 /* Write STR, with a leading space to BUFFER, updating COLUMN as appropriate.
156 COLMAX is the number of columns to word-wrap at (0 means don't wrap). */
157
158 static void
159 deps_write_string (const char *str, obstack *buffer, unsigned &column,
160 unsigned colmax = 72)
161 {
162 unsigned size = strlen (str);
163
164 if (column != 0)
165 {
166 if (colmax && column + size > colmax)
167 {
168 obstack_grow (buffer, " \\\n ", 4);
169 column = 1;
170 }
171 else
172 {
173 obstack_1grow (buffer, ' ');
174 column++;
175 }
176 }
177
178 column += size;
179 obstack_grow (buffer, str, size);
180 }
181
182 /* Write out all dependencies of a given MODULE to the specified BUFFER. */
183
184 static void
185 deps_write (Module *module, obstack *buffer)
186 {
187 hash_set <const char *> seen_modules;
188 vec <const char *> dependencies = vNULL;
189
190 Modules modlist;
191 modlist.push (module);
192
193 vec <const char *> phonylist = vNULL;
194 unsigned column = 0;
195
196 /* Write out make target module name. */
197 if (d_option.deps_target.length ())
198 {
199 for (unsigned i = 0; i < d_option.deps_target.length (); i++)
200 deps_write_string (d_option.deps_target[i], buffer, column);
201 }
202 else
203 deps_write_string (module->objfile.toChars (), buffer, column);
204
205 obstack_1grow (buffer, ':');
206 column++;
207
208 /* Search all modules for file dependencies. */
209 while (modlist.length > 0)
210 {
211 Module *depmod = modlist.pop ();
212
213 const char *modstr = depmod->srcfile.toChars ();
214
215 /* Skip modules that have already been looked at. */
216 if (seen_modules.add (modstr))
217 continue;
218
219 dependencies.safe_push (modstr);
220
221 /* Add to list of phony targets if is not being compile. */
222 if (d_option.deps_phony && !depmod->isRoot ())
223 phonylist.safe_push (modstr);
224
225 /* Add imported files to dependency list. */
226 for (size_t i = 0; i < depmod->contentImportedFiles.length; i++)
227 {
228 const char *impstr = depmod->contentImportedFiles[i];
229 dependencies.safe_push (impstr);
230 phonylist.safe_push (impstr);
231 }
232
233 /* Search all imports of the module. */
234 for (size_t i = 0; i < depmod->aimports.length; i++)
235 {
236 Module *m = depmod->aimports[i];
237
238 /* Ignore compiler-generated modules. */
239 if (m->ident == Identifier::idPool ("__main") && m->parent == NULL)
240 continue;
241
242 /* Don't search system installed modules, this includes
243 object, core.*, std.*, and gcc.* packages. */
244 if (d_option.deps_skip_system)
245 {
246 if (m->ident == Identifier::idPool ("object")
247 && m->parent == NULL)
248 continue;
249
250 if (m->md && m->md->packages.length)
251 {
252 Identifier *package = m->md->packages.ptr[0];
253
254 if (package == Identifier::idPool ("core")
255 || package == Identifier::idPool ("std")
256 || package == Identifier::idPool ("gcc"))
257 continue;
258 }
259 }
260
261 modlist.push (m);
262 }
263 }
264
265 /* Write out all make dependencies. */
266 for (size_t i = 0; i < dependencies.length (); i++)
267 deps_write_string (dependencies[i], buffer, column);
268
269 obstack_1grow (buffer, '\n');
270
271 /* Write out all phony targets. */
272 for (size_t i = 0; i < phonylist.length (); i++)
273 {
274 const char *str = phonylist[i];
275 obstack_1grow (buffer, '\n');
276 obstack_grow (buffer, str, strlen (str));
277 obstack_grow (buffer, ":\n", 2);
278 }
279
280 obstack_1grow (buffer, '\0');
281 }
282
283 /* Implements the lang_hooks.init_options routine for language D.
284 This initializes the global state for the D frontend before calling
285 the option handlers. */
286
287 static void
288 d_init_options (unsigned int, cl_decoded_option *decoded_options)
289 {
290 /* Initialize the D runtime. */
291 rt_init ();
292 gc_disable ();
293
294 /* Set default values. */
295 global._init ();
296
297 global.compileEnv.vendor = lang_hooks.name;
298 global.params.argv0 = xstrdup (decoded_options[0].arg);
299
300 /* Default extern(C++) mangling to C++17. */
301 global.params.cplusplus = CppStdRevisionCpp17;
302
303 /* Warnings and deprecations are disabled by default. */
304 global.params.useDeprecated = DIAGNOSTICinform;
305 global.params.useWarnings = DIAGNOSTICoff;
306 global.params.v.errorLimit = flag_max_errors;
307 global.params.v.messageStyle = MessageStyle::gnu;
308
309 /* Extra GDC-specific options. */
310 d_option.fonly = NULL;
311 d_option.multilib = NULL;
312 d_option.prefix = NULL;
313 d_option.deps = false;
314 d_option.deps_skip_system = false;
315 d_option.deps_filename = NULL;
316 d_option.deps_filename_user = NULL;
317 d_option.deps_target = vNULL;
318 d_option.deps_phony = false;
319 d_option.stdinc = true;
320 }
321
322 /* Implements the lang_hooks.init_options_struct routine for language D.
323 Initializes the options structure OPTS. */
324
325 static void
326 d_init_options_struct (gcc_options *opts)
327 {
328 /* GCC options. */
329 opts->x_flag_exceptions = 1;
330
331 /* Unlike C, there is no global `errno' variable. */
332 opts->x_flag_errno_math = 0;
333 opts->frontend_set_flag_errno_math = true;
334
335 /* D says that signed overflow is precisely defined. */
336 opts->x_flag_wrapv = 1;
337 }
338
339 /* Implements the lang_hooks.lang_mask routine for language D.
340 Returns language mask for option parsing. */
341
342 static unsigned int
343 d_option_lang_mask (void)
344 {
345 return CL_D;
346 }
347
348 /* Implements input charset and BOM skipping configuration for
349 diagnostics. */
350 static const char *d_input_charset_callback (const char * /*filename*/)
351 {
352 /* TODO: The input charset is automatically determined by code in
353 dmd/dmodule.c based on the contents of the file. If this detection
354 logic were factored out and could be reused here, then we would be able
355 to return UTF-16 or UTF-32 as needed here. For now, we return always
356 NULL, which means no conversion is necessary, i.e. the input is assumed
357 to be UTF-8 when diagnostics read this file. */
358 return nullptr;
359 }
360
361 /* Implements the lang_hooks.init routine for language D. */
362
363 static bool
364 d_init (void)
365 {
366 Type::_init ();
367 Id::initialize ();
368 Module::_init ();
369 Expression::_init ();
370 Objc::_init ();
371
372 /* Diagnostics input init, to enable BOM skipping and
373 input charset conversion. */
374 diagnostic_initialize_input_context (global_dc,
375 d_input_charset_callback, true);
376
377 /* Back-end init. */
378 global_binding_level = ggc_cleared_alloc <binding_level> ();
379 current_binding_level = global_binding_level;
380
381 /* This allows the code in d-builtins.cc to not have to worry about
382 converting (C signed char *) to (D char *) for string arguments of
383 built-in functions. The parameter (signed_char = false) specifies
384 whether char is signed. */
385 build_common_tree_nodes (false);
386
387 d_init_builtins ();
388
389 if (flag_exceptions)
390 using_eh_for_cleanups ();
391
392 if (!supports_one_only ())
393 flag_weak_templates = 0;
394
395 /* This is the C main, not the D main. */
396 main_identifier_node = get_identifier ("main");
397
398 target._init (global.params);
399 d_init_versions ();
400
401 /* Insert all library-configured identifiers and import paths. */
402 add_import_paths (d_option.prefix, d_option.multilib, d_option.stdinc);
403
404 return 1;
405 }
406
407 /* Implements the lang_hooks.init_ts routine for language D. */
408
409 static void
410 d_init_ts (void)
411 {
412 MARK_TS_TYPED (FLOAT_MOD_EXPR);
413 MARK_TS_TYPED (UNSIGNED_RSHIFT_EXPR);
414 }
415
416 /* Implements the lang_hooks.handle_option routine for language D.
417 Handles D specific options. Return false if we didn't do anything. */
418
419 static bool
420 d_handle_option (size_t scode, const char *arg, HOST_WIDE_INT value,
421 int kind ATTRIBUTE_UNUSED,
422 location_t loc ATTRIBUTE_UNUSED,
423 const cl_option_handlers *handlers ATTRIBUTE_UNUSED)
424 {
425 opt_code code = (opt_code) scode;
426 bool result = true;
427
428 switch (code)
429 {
430 case OPT_fall_instantiations:
431 global.params.allInst = value;
432 break;
433
434 case OPT_fassert:
435 global.params.useAssert = value ? CHECKENABLEon : CHECKENABLEoff;
436 break;
437
438 case OPT_fbounds_check:
439 global.params.useArrayBounds = value ? CHECKENABLEon : CHECKENABLEoff;
440 break;
441
442 case OPT_fbounds_check_:
443 global.params.useArrayBounds = (value == 2) ? CHECKENABLEon
444 : (value == 1) ? CHECKENABLEsafeonly : CHECKENABLEoff;
445 break;
446
447 case OPT_fcheckaction_:
448 global.params.checkAction = (value == 0) ? CHECKACTION_D
449 : (value == 1) ? CHECKACTION_halt : CHECKACTION_context;
450 break;
451
452 case OPT_fdebug:
453 global.params.debugEnabled = value ? true : false;
454 break;
455
456 case OPT_fdebug_:
457 if (Identifier::isValidIdentifier (CONST_CAST (char *, arg)))
458 {
459 DebugCondition::addGlobalIdent (arg);
460 break;
461 }
462
463 error ("bad argument for %<-fdebug=%>: %qs", arg);
464 break;
465
466 case OPT_fdoc:
467 global.params.ddoc.doOutput = value;
468 break;
469
470 case OPT_fdoc_dir_:
471 global.params.ddoc.doOutput = true;
472 global.params.ddoc.dir = arg;
473 break;
474
475 case OPT_fdoc_file_:
476 global.params.ddoc.doOutput = true;
477 global.params.ddoc.name = arg;
478 break;
479
480 case OPT_fdoc_inc_:
481 global.params.ddoc.files.push (arg);
482 break;
483
484 case OPT_fdruntime:
485 global.params.betterC = !value;
486 break;
487
488 case OPT_fdump_c___spec_:
489 global.params.cxxhdr.doOutput = true;
490 global.params.cxxhdr.name = arg;
491 break;
492
493 case OPT_fdump_c___spec_verbose:
494 global.params.cxxhdr.fullOutput = true;
495 break;
496
497 case OPT_fdump_d_original:
498 global.params.vcg_ast = value;
499 break;
500
501 case OPT_fexceptions:
502 global.params.useExceptions = value;
503 break;
504
505 case OPT_fextern_std_:
506 switch (value)
507 {
508 case CppStdRevisionCpp98:
509 case CppStdRevisionCpp11:
510 case CppStdRevisionCpp14:
511 case CppStdRevisionCpp17:
512 case CppStdRevisionCpp20:
513 case CppStdRevisionCpp23:
514 global.params.cplusplus = (CppStdRevision) value;
515 break;
516
517 default:
518 error ("bad argument for %<-fextern-std%>: %qs", arg);
519 }
520 break;
521
522 case OPT_fignore_unknown_pragmas:
523 global.params.ignoreUnsupportedPragmas = value;
524 break;
525
526 case OPT_finclude_imports:
527 includeImports = true;
528 break;
529
530 case OPT_finvariants:
531 global.params.useInvariants = value ? CHECKENABLEon : CHECKENABLEoff;
532 break;
533
534 case OPT_fmain:
535 global.params.addMain = value;
536 break;
537
538 case OPT_fmodule_file_:
539 global.params.modFileAliasStrings.push (arg);
540 if (!strchr (arg, '='))
541 error ("bad argument for %<-fmodule-file=%>: %qs", arg);
542 break;
543
544 case OPT_fmoduleinfo:
545 global.params.useModuleInfo = value;
546 break;
547
548 case OPT_fonly_:
549 d_option.fonly = arg;
550 break;
551
552 case OPT_fpostconditions:
553 global.params.useOut = value ? CHECKENABLEon : CHECKENABLEoff;
554 break;
555
556 case OPT_fpreconditions:
557 global.params.useIn = value ? CHECKENABLEon : CHECKENABLEoff;
558 break;
559
560 case OPT_fpreview_all:
561 global.params.ehnogc = value;
562 global.params.useDIP1000 = FeatureState::enabled;
563 global.params.useDIP1021 = value;
564 global.params.bitfields = value;
565 global.params.dtorFields = FeatureState::enabled;
566 global.params.fieldwise = FeatureState::enabled;
567 global.params.fixAliasThis = value;
568 global.params.previewIn = value;
569 global.params.fix16997 = value;
570 global.params.noSharedAccess = FeatureState::enabled;
571 global.params.safer = FeatureState::enabled;
572 global.params.rvalueRefParam = FeatureState::enabled;
573 global.params.inclusiveInContracts = value;
574 global.params.systemVariables = FeatureState::enabled;
575 global.params.fixImmutableConv = value;
576 break;
577
578 case OPT_fpreview_bitfields:
579 global.params.bitfields = value;
580 break;
581
582 case OPT_fpreview_dip1000:
583 global.params.useDIP1000 = FeatureState::enabled;
584 break;
585
586 case OPT_fpreview_dip1008:
587 global.params.ehnogc = value;
588 break;
589
590 case OPT_fpreview_dip1021:
591 global.params.useDIP1021 = value;
592 break;
593
594 case OPT_fpreview_dtorfields:
595 global.params.dtorFields = FeatureState::enabled;
596 break;
597
598 case OPT_fpreview_fieldwise:
599 global.params.fieldwise = FeatureState::enabled;
600 break;
601
602 case OPT_fpreview_fixaliasthis:
603 global.params.fixAliasThis = value;
604 break;
605
606 case OPT_fpreview_fiximmutableconv:
607 global.params.fixImmutableConv = value;
608 break;
609
610 case OPT_fpreview_in:
611 global.params.previewIn = value;
612 break;
613
614 case OPT_fpreview_inclusiveincontracts:
615 global.params.inclusiveInContracts = value;
616 break;
617
618 case OPT_fpreview_nosharedaccess:
619 global.params.noSharedAccess = FeatureState::enabled;
620 break;
621
622 case OPT_fpreview_safer:
623 global.params.safer = FeatureState::enabled;
624 break;
625
626 case OPT_fpreview_rvaluerefparam:
627 global.params.rvalueRefParam = FeatureState::enabled;
628 break;
629
630 case OPT_fpreview_systemvariables:
631 global.params.systemVariables = FeatureState::enabled;
632 break;
633
634 case OPT_frelease:
635 global.params.release = value;
636 break;
637
638 case OPT_frevert_all:
639 global.params.useDIP1000 = FeatureState::disabled;
640 global.params.dtorFields = FeatureState::disabled;
641 global.params.fix16997 = !value;
642 break;
643
644 case OPT_frevert_dip1000:
645 global.params.useDIP1000 = FeatureState::disabled;
646 break;
647
648 case OPT_frevert_dtorfields:
649 global.params.dtorFields = FeatureState::disabled;
650 break;
651
652 case OPT_frevert_intpromote:
653 global.params.fix16997 = !value;
654 break;
655
656 case OPT_frtti:
657 global.params.useTypeInfo = value;
658 break;
659
660 case OPT_fsave_mixins_:
661 global.params.mixinOut.doOutput = true;
662 global.params.mixinOut.name = arg;
663 global.params.mixinOut.buffer = d_gc_malloc<OutBuffer> ();
664 break;
665
666 case OPT_fswitch_errors:
667 global.params.useSwitchError = value ? CHECKENABLEon : CHECKENABLEoff;
668 break;
669
670 case OPT_ftransition_all:
671 global.params.v.field = value;
672 global.params.v.gc = value;
673 global.params.v.vin = value;
674 global.params.v.tls = value;
675 break;
676
677 case OPT_ftransition_field:
678 global.params.v.field = value;
679 break;
680
681 case OPT_ftransition_in:
682 global.params.v.vin = value;
683 break;
684
685 case OPT_ftransition_nogc:
686 global.params.v.gc = value;
687 break;
688
689 case OPT_ftransition_templates:
690 global.params.v.templates = value;
691 break;
692
693 case OPT_ftransition_tls:
694 global.params.v.tls = value;
695 break;
696
697 case OPT_funittest:
698 global.params.useUnitTests = value;
699 break;
700
701 case OPT_fversion_:
702 if (Identifier::isValidIdentifier (CONST_CAST (char *, arg)))
703 {
704 VersionCondition::addGlobalIdent (arg);
705 break;
706 }
707
708 error ("bad argument for %<-fversion=%>: %qs", arg);
709 break;
710
711 case OPT_H:
712 global.params.dihdr.doOutput = true;
713 break;
714
715 case OPT_Hd:
716 global.params.dihdr.doOutput = true;
717 global.params.dihdr.dir = arg;
718 break;
719
720 case OPT_Hf:
721 global.params.dihdr.doOutput = true;
722 global.params.dihdr.name = arg;
723 break;
724
725 case OPT_imultilib:
726 d_option.multilib = arg;
727 break;
728
729 case OPT_iprefix:
730 d_option.prefix = arg;
731 break;
732
733 case OPT_I:
734 global.params.imppath.push (arg);
735 break;
736
737 case OPT_J:
738 global.params.fileImppath.push (arg);
739 break;
740
741 case OPT_MM:
742 d_option.deps_skip_system = true;
743 /* Fall through. */
744
745 case OPT_M:
746 d_option.deps = true;
747 break;
748
749 case OPT_MMD:
750 d_option.deps_skip_system = true;
751 /* Fall through. */
752
753 case OPT_MD:
754 d_option.deps = true;
755 d_option.deps_filename = arg;
756 break;
757
758 case OPT_MF:
759 /* If specified multiple times, last one wins. */
760 d_option.deps_filename_user = arg;
761 break;
762
763 case OPT_MP:
764 d_option.deps_phony = true;
765 break;
766
767 case OPT_MQ:
768 deps_add_target (arg, true);
769 break;
770
771 case OPT_MT:
772 deps_add_target (arg, false);
773 break;
774
775 case OPT_nostdinc:
776 d_option.stdinc = false;
777 break;
778
779 case OPT_v:
780 global.params.v.verbose = value;
781 break;
782
783 case OPT_Wall:
784 if (value)
785 global.params.useWarnings = DIAGNOSTICinform;
786 break;
787
788 case OPT_Wdeprecated:
789 global.params.useDeprecated = value ? DIAGNOSTICinform : DIAGNOSTICoff;
790 break;
791
792 case OPT_Werror:
793 if (value)
794 global.params.useWarnings = DIAGNOSTICerror;
795 break;
796
797 case OPT_Wspeculative:
798 if (value)
799 global.params.v.showGaggedErrors = 1;
800 break;
801
802 case OPT_Xf:
803 global.params.json.name = arg;
804 /* Fall through. */
805
806 case OPT_X:
807 global.params.json.doOutput = true;
808 break;
809
810 default:
811 break;
812 }
813
814 D_handle_option_auto (&global_options, &global_options_set,
815 scode, arg, value,
816 d_option_lang_mask (), kind,
817 loc, handlers, global_dc);
818
819 return result;
820 }
821
822 /* Implements the lang_hooks.post_options routine for language D.
823 Deal with any options that imply the turning on/off of features.
824 FN is the main input filename passed on the command line. */
825
826 static bool
827 d_post_options (const char ** fn)
828 {
829 /* Verify the input file name. */
830 const char *filename = *fn;
831 if (!filename || strcmp (filename, "-") == 0)
832 filename = "";
833
834 /* The front end considers the first input file to be the main one. */
835 *fn = filename;
836
837 /* Release mode doesn't turn off bounds checking for safe functions. */
838 if (global.params.useArrayBounds == CHECKENABLEdefault)
839 {
840 global.params.useArrayBounds = global.params.release
841 ? CHECKENABLEsafeonly : CHECKENABLEon;
842 }
843
844 /* Assert code is generated if unittests are being compiled also, even if
845 release mode is turned on. */
846 if (global.params.useAssert == CHECKENABLEdefault)
847 {
848 if (global.params.useUnitTests || !global.params.release)
849 global.params.useAssert = CHECKENABLEon;
850 else
851 global.params.useAssert = CHECKENABLEoff;
852 }
853
854 /* Checks for switches without a default are turned off in release mode. */
855 if (global.params.useSwitchError == CHECKENABLEdefault)
856 {
857 global.params.useSwitchError = global.params.release
858 ? CHECKENABLEoff : CHECKENABLEon;
859 }
860
861 /* Contracts are turned off in release mode. */
862 if (global.params.useInvariants == CHECKENABLEdefault)
863 {
864 global.params.useInvariants = global.params.release
865 ? CHECKENABLEoff : CHECKENABLEon;
866 }
867
868 if (global.params.useIn == CHECKENABLEdefault)
869 {
870 global.params.useIn = global.params.release
871 ? CHECKENABLEoff : CHECKENABLEon;
872 }
873
874 if (global.params.useOut == CHECKENABLEdefault)
875 {
876 global.params.useOut = global.params.release
877 ? CHECKENABLEoff : CHECKENABLEon;
878 }
879
880 /* When not linking against D runtime, turn off all code generation that
881 would otherwise reference it. */
882 if (global.params.betterC)
883 {
884 if (!OPTION_SET_P (flag_moduleinfo))
885 global.params.useModuleInfo = false;
886
887 /* Ensure that the front-end options are in sync with the `-frtti' and
888 `-fexceptions' flags. */
889 if (!OPTION_SET_P (flag_rtti))
890 {
891 global.params.useTypeInfo = false;
892 flag_rtti = false;
893 }
894
895 if (!OPTION_SET_P (flag_exceptions))
896 {
897 global.params.useExceptions = false;
898 flag_exceptions = false;
899 }
900
901 global.params.useGC = false;
902 global.params.checkAction = CHECKACTION_C;
903 }
904
905 /* Enabling DIP1021 implies DIP1000. */
906 if (global.params.useDIP1021)
907 global.params.useDIP1000 = FeatureState::enabled;
908
909 /* Keep in sync with existing -fbounds-check flag. */
910 flag_bounds_check = (global.params.useArrayBounds == CHECKENABLEon);
911
912 /* Turn off partitioning unless it was explicitly requested, as it doesn't
913 work with D exception chaining, where EH handler uses LSDA to determine
914 whether two thrown exception are in the same context. */
915 if (!OPTION_SET_P (flag_reorder_blocks_and_partition))
916 global_options.x_flag_reorder_blocks_and_partition = 0;
917
918 /* Error about use of deprecated features. */
919 if (global.params.useDeprecated == DIAGNOSTICinform
920 && global.params.useWarnings == DIAGNOSTICerror)
921 global.params.useDeprecated = DIAGNOSTICerror;
922
923 if (flag_excess_precision == EXCESS_PRECISION_DEFAULT)
924 flag_excess_precision = EXCESS_PRECISION_STANDARD;
925
926 global.params.useInline = flag_inline_functions;
927
928 /* Make -fmax-errors visible to frontend's diagnostic machinery. */
929 if (OPTION_SET_P (flag_max_errors))
930 global.params.v.errorLimit = flag_max_errors;
931
932 global.params.v.showColumns = flag_show_column;
933 global.params.v.errorPrintMode = flag_diagnostics_show_caret
934 ? ErrorPrintMode::printErrorContext : ErrorPrintMode::simpleError;
935
936 /* Keep the front-end location type in sync with params. */
937 Loc::set (global.params.v.showColumns, global.params.v.messageStyle);
938
939 if (global.params.useInline)
940 global.params.dihdr.fullOutput = true;
941
942 global.params.obj = !flag_syntax_only;
943
944 /* The front-end parser only has access to `compileEnv', synchronize its
945 fields with params. */
946 global.compileEnv.previewIn = global.params.previewIn;
947 global.compileEnv.transitionIn = global.params.v.vin;
948 global.compileEnv.ddocOutput = global.params.ddoc.doOutput;
949 global.compileEnv.cCharLookupTable =
950 IdentifierCharLookup::forTable (IdentifierTable::C11);
951 global.compileEnv.dCharLookupTable =
952 IdentifierCharLookup::forTable (IdentifierTable::LR);
953
954 if (warn_return_type == -1)
955 warn_return_type = 0;
956
957 return false;
958 }
959
960 /* Add the module M to the list of modules that may declare GCC builtins.
961 These are scanned after first semantic and before codegen passes.
962 See d_maybe_set_builtin() for the implementation. */
963
964 void
965 d_add_builtin_module (Module *m)
966 {
967 builtin_modules.push (m);
968 }
969
970 /* Writes to FILENAME. DATA is the full content of the file to be written. */
971
972 static void
973 d_write_file (const char *filename, const char *data)
974 {
975 FILE *stream;
976
977 if (filename && (filename[0] != '-' || filename[1] != '\0'))
978 stream = fopen (filename, "w");
979 else
980 stream = stdout;
981
982 if (!stream)
983 {
984 error ("unable to open %s for writing: %m", filename);
985 return;
986 }
987
988 fprintf (stream, "%s", data);
989
990 if (stream != stdout && (ferror (stream) || fclose (stream)))
991 error ("writing output file %s: %m", filename);
992 }
993
994 /* Read ddoc macro files named by the DDOCFILES, then write the concatenated
995 the contents into DDOCBUF. */
996
997 static void
998 d_read_ddoc_files (Strings &ddocfiles, OutBuffer &ddocbuf)
999 {
1000 if (ddocbuf.length ())
1001 return;
1002
1003 for (size_t i = 0; i < ddocfiles.length; i++)
1004 {
1005 int fd = open (ddocfiles[i], O_RDONLY);
1006 bool ok = false;
1007 struct stat buf;
1008
1009 if (fd == -1 || fstat (fd, &buf))
1010 {
1011 error ("unable to open %s for reading: %m", ddocfiles[i]);
1012 continue;
1013 }
1014
1015 /* Check we've not been given a directory, or a file bigger than 4GB. */
1016 if (S_ISDIR (buf.st_mode))
1017 errno = ENOENT;
1018 else if (buf.st_size != unsigned (buf.st_size))
1019 errno = EMFILE;
1020 else
1021 {
1022 unsigned size = unsigned (buf.st_size);
1023 char *buffer = (char *) xmalloc (size);
1024
1025 if (read (fd, buffer, size) == ssize_t (size))
1026 {
1027 ddocbuf.write (buffer, size);
1028 ok = true;
1029 }
1030
1031 free (buffer);
1032 }
1033
1034 close (fd);
1035 if (!ok)
1036 fatal_error (input_location, "reading ddoc file %s: %m", ddocfiles[i]);
1037 }
1038 }
1039
1040 static void
1041 d_generate_ddoc_file (Module *m, OutBuffer &ddocbuf)
1042 {
1043 input_location = make_location_t (m->loc);
1044
1045 d_read_ddoc_files (global.params.ddoc.files, ddocbuf);
1046
1047 OutBuffer ddocbuf_out;
1048 dmd::gendocfile (m, ddocbuf.peekChars (), ddocbuf.length (), global.datetime,
1049 global.errorSink, ddocbuf_out);
1050
1051 d_write_file (m->docfile.toChars (), ddocbuf_out.peekChars ());
1052 }
1053
1054 /* Implements the lang_hooks.parse_file routine for language D. */
1055
1056 static void
1057 d_parse_file (void)
1058 {
1059 if (global.params.v.verbose)
1060 {
1061 /* Dump information about the D compiler and language version. */
1062 message ("binary %s", global.params.argv0.ptr);
1063 message ("version %s", global.versionChars ());
1064
1065 /* Dump all predefined version identifiers. */
1066 obstack buffer;
1067 gcc_obstack_init (&buffer);
1068 obstack_grow (&buffer, "predefs ", 9);
1069 for (size_t i = 0; i < global.versionids.length; i++)
1070 {
1071 Identifier *id = global.versionids[i];
1072 const char *str = id->toChars ();
1073 obstack_1grow (&buffer, ' ');
1074 obstack_grow (&buffer, str, strlen (str));
1075 }
1076
1077 obstack_1grow (&buffer, '\0');
1078 message ("%s", (char *) obstack_finish (&buffer));
1079 }
1080
1081 /* Start the main input file, if the debug writer wants it. */
1082 if (debug_hooks->start_end_main_source_file)
1083 debug_hooks->start_source_file (0, main_input_filename);
1084
1085 /* Create Module's for all sources we will load. */
1086 Modules modules;
1087 modules.reserve (num_in_fnames);
1088
1089 /* Buffer for contents of .ddoc files. */
1090 OutBuffer ddocbuf;
1091
1092 /* In this mode, the main input file is supposed to be the same as the one
1093 given by -fonly=. */
1094 if (d_option.fonly && !endswith (main_input_filename, d_option.fonly))
1095 error ("%<-fonly=%> argument is different from first input file name");
1096
1097 for (size_t i = 0; i < num_in_fnames; i++)
1098 {
1099 if (strcmp (in_fnames[i], "-") == 0)
1100 {
1101 /* Load the entire contents of stdin into memory. 8 kilobytes should
1102 be a good enough initial size, but double on each iteration.
1103 16 bytes are added for the final '\n' and 15 bytes of padding. */
1104 ssize_t size = 8 * 1024;
1105 uchar *buffer = XNEWVEC (uchar, size + 16);
1106 ssize_t len = 0;
1107 ssize_t count;
1108
1109 while ((count = read (STDIN_FILENO, buffer + len, size - len)) > 0)
1110 {
1111 len += count;
1112 if (len == size)
1113 {
1114 size *= 2;
1115 buffer = XRESIZEVEC (uchar, buffer, size + 16);
1116 }
1117 }
1118
1119 if (count < 0)
1120 {
1121 error (Loc::singleFilename ("stdin"), "%s", xstrerror (errno));
1122 free (buffer);
1123 continue;
1124 }
1125
1126 /* Handling stdin, generate a unique name for the module. */
1127 Module *m = Module::create (in_fnames[i],
1128 Identifier::idPool ("__stdin"),
1129 global.params.ddoc.doOutput,
1130 global.params.dihdr.doOutput);
1131 m->loc = Loc::singleFilename (in_fnames[i]);
1132 modules.push (m);
1133
1134 /* Zero the padding past the end of the buffer so the D lexer has a
1135 sentinel. The lexer only reads up to 4 bytes at a time. */
1136 memset (buffer + len, '\0', 16);
1137
1138 /* Overwrite the source file for the module, the one created by
1139 Module::create would have a forced a `.d' suffix. */
1140 m->src.length = len;
1141 m->src.ptr = buffer;
1142 }
1143 else
1144 {
1145 /* Handling a D source file, strip off the path and extension. */
1146 const char *basename = FileName::name (in_fnames[i]);
1147 const char *name = FileName::removeExt (basename);
1148
1149 Module *m = Module::create (in_fnames[i], Identifier::idPool (name),
1150 global.params.ddoc.doOutput,
1151 global.params.dihdr.doOutput);
1152 m->loc = Loc::singleFilename (in_fnames[i]);
1153 modules.push (m);
1154 FileName::free (name);
1155 }
1156 }
1157
1158 /* Read all D source files. */
1159 for (size_t i = 0; i < modules.length; i++)
1160 {
1161 Module *m = modules[i];
1162 m->read (Loc ());
1163 }
1164
1165 /* Parse all D source files. */
1166 for (size_t i = 0; i < modules.length; i++)
1167 {
1168 Module *m = modules[i];
1169
1170 if (global.params.v.verbose)
1171 message ("parse %s", m->toChars ());
1172
1173 if (!Module::rootModule)
1174 Module::rootModule = m;
1175
1176 m->importedFrom = m;
1177 m->parse ();
1178
1179 if (m->filetype == FileType::ddoc)
1180 {
1181 d_generate_ddoc_file (m, ddocbuf);
1182
1183 /* Remove M from list of modules. */
1184 modules.remove (i);
1185 i--;
1186 }
1187 }
1188
1189 /* Load the module containing D main. */
1190 Module *main_module = NULL;
1191 if (global.params.addMain)
1192 {
1193 unsigned errors = global.startGagging ();
1194 main_module = Module::load (Loc (), NULL, Identifier::idPool ("__main"));
1195
1196 if (!global.endGagging (errors))
1197 {
1198 main_module->importedFrom = main_module;
1199 modules.push (main_module);
1200 }
1201 }
1202
1203 /* If an error occurs later during compilation, remember that we generated
1204 the headers, so that they can be removed before exit. */
1205 bool dump_headers = false;
1206
1207 if (global.errors)
1208 goto had_errors;
1209
1210 if (global.params.dihdr.doOutput)
1211 {
1212 /* Generate 'header' import files. Since 'header' import files must be
1213 independent of command line switches and what else is imported, they
1214 are generated before any semantic analysis. */
1215 for (size_t i = 0; i < modules.length; i++)
1216 {
1217 Module *m = modules[i];
1218 if (m->filetype == FileType::dhdr
1219 || (d_option.fonly && m != Module::rootModule))
1220 continue;
1221
1222 if (global.params.v.verbose)
1223 message ("import %s", m->toChars ());
1224
1225 OutBuffer buf;
1226 dmd::genhdrfile (m, global.params.dihdr.fullOutput, buf);
1227 d_write_file (m->hdrfile.toChars (), buf.peekChars ());
1228 }
1229
1230 dump_headers = true;
1231 }
1232
1233 if (global.errors)
1234 goto had_errors;
1235
1236 /* Load all unconditional imports for better symbol resolving. */
1237 for (size_t i = 0; i < modules.length; i++)
1238 {
1239 Module *m = modules[i];
1240
1241 if (global.params.v.verbose)
1242 message ("importall %s", m->toChars ());
1243
1244 dmd::importAll (m, NULL);
1245 }
1246
1247 if (global.errors)
1248 goto had_errors;
1249
1250 /* Do semantic analysis. */
1251 doing_semantic_analysis_p = true;
1252
1253 for (size_t i = 0; i < modules.length; i++)
1254 {
1255 Module *m = modules[i];
1256
1257 /* If this is the `__main` module, check that `D main` hasn't already
1258 been declared in user code before running semantic on it. */
1259 if (m == main_module && global.hasMainFunction)
1260 {
1261 modules.remove (i);
1262 continue;
1263 }
1264
1265 if (global.params.v.verbose)
1266 message ("semantic %s", m->toChars ());
1267
1268 dmd::dsymbolSemantic (m, NULL);
1269 }
1270
1271 /* Do deferred semantic analysis. */
1272 Module::runDeferredSemantic ();
1273
1274 if (Module::deferred.length)
1275 {
1276 for (size_t i = 0; i < Module::deferred.length; i++)
1277 {
1278 Dsymbol *sd = Module::deferred[i];
1279 error_at (make_location_t (sd->loc),
1280 "unable to resolve forward reference in definition");
1281 }
1282 }
1283
1284 /* Process all built-in modules or functions now for CTFE. */
1285 while (builtin_modules.length != 0)
1286 {
1287 Module *m = builtin_modules.pop ();
1288 d_maybe_set_builtin (m);
1289 }
1290
1291 /* Do pass 2 semantic analysis. */
1292 for (size_t i = 0; i < modules.length; i++)
1293 {
1294 Module *m = modules[i];
1295
1296 if (global.params.v.verbose)
1297 message ("semantic2 %s", m->toChars ());
1298
1299 dmd::semantic2 (m, NULL);
1300 }
1301
1302 Module::runDeferredSemantic2 ();
1303
1304 if (global.errors)
1305 goto had_errors;
1306
1307 /* Do pass 3 semantic analysis. */
1308 for (size_t i = 0; i < modules.length; i++)
1309 {
1310 Module *m = modules[i];
1311
1312 if (global.params.v.verbose)
1313 message ("semantic3 %s", m->toChars ());
1314
1315 dmd::semantic3 (m, NULL);
1316 }
1317
1318 if (includeImports)
1319 {
1320 for (size_t i = 0; i < compiledImports.length; i++)
1321 {
1322 Module *m = compiledImports[i];
1323 gcc_assert (m->isRoot ());
1324
1325 if (global.params.v.verbose)
1326 message ("semantic3 %s", m->toChars ());
1327
1328 dmd::semantic3 (m, NULL);
1329 modules.push (m);
1330 }
1331 }
1332
1333 Module::runDeferredSemantic3 ();
1334
1335 /* Check again, incase semantic3 pass loaded any more modules. */
1336 while (builtin_modules.length != 0)
1337 {
1338 Module *m = builtin_modules.pop ();
1339 d_maybe_set_builtin (m);
1340 }
1341
1342 /* Do not attempt to generate output files if errors or warnings occurred. */
1343 if (global.errors || global.warnings)
1344 goto had_errors;
1345
1346 /* Generate output files. */
1347 doing_semantic_analysis_p = false;
1348
1349 if (Module::rootModule)
1350 {
1351 /* Declare the name of the root module as the first global name in order
1352 to make the middle-end fully deterministic. */
1353 OutBuffer buf;
1354 dmd::mangleToBuffer (Module::rootModule, buf);
1355 first_global_object_name = buf.extractChars ();
1356 }
1357
1358 /* Make dependencies. */
1359 if (d_option.deps)
1360 {
1361 obstack buffer;
1362 gcc_obstack_init (&buffer);
1363
1364 for (size_t i = 0; i < modules.length; i++)
1365 deps_write (modules[i], &buffer);
1366
1367 /* -MF <arg> overrides -M[M]D. */
1368 if (d_option.deps_filename_user)
1369 d_option.deps_filename = d_option.deps_filename_user;
1370
1371 d_write_file (d_option.deps_filename,
1372 (char *) obstack_finish (&buffer));
1373 }
1374
1375 if (global.params.v.templates)
1376 {
1377 dmd::printTemplateStats (global.params.v.templatesListInstances,
1378 global.errorSink);
1379 }
1380
1381 /* Generate JSON files. */
1382 if (global.params.json.doOutput)
1383 {
1384 OutBuffer buf;
1385 dmd::json_generate (modules, buf);
1386 d_write_file (global.params.json.name.ptr, buf.peekChars ());
1387 }
1388
1389 /* Generate Ddoc files. */
1390 if (global.params.ddoc.doOutput && !global.errors && !errorcount)
1391 {
1392 for (size_t i = 0; i < modules.length; i++)
1393 {
1394 Module *m = modules[i];
1395 d_generate_ddoc_file (m, ddocbuf);
1396 }
1397 }
1398
1399 /* Handle -fdump-d-original. */
1400 if (global.params.vcg_ast)
1401 {
1402 for (size_t i = 0; i < modules.length; i++)
1403 {
1404 Module *m = modules[i];
1405 OutBuffer buf;
1406 buf.doindent = 1;
1407
1408 dmd::moduleToBuffer (buf, true, m);
1409 message ("%s", buf.peekChars ());
1410 }
1411 }
1412
1413 /* Generate C++ header files. */
1414 if (global.params.cxxhdr.doOutput)
1415 dmd::genCppHdrFiles (modules);
1416
1417 if (global.errors)
1418 goto had_errors;
1419
1420 for (size_t i = 0; i < modules.length; i++)
1421 {
1422 Module *m = modules[i];
1423
1424 /* Skip generating code for header files, or when the module wasn't
1425 specified by `-fonly=`. */
1426 if ((m->filetype == FileType::dhdr && m != main_module)
1427 || (d_option.fonly && m != Module::rootModule))
1428 continue;
1429
1430 if (global.params.v.verbose)
1431 message ("code %s", m->toChars ());
1432
1433 if (!flag_syntax_only)
1434 build_decl_tree (m);
1435 }
1436
1437 /* And end the main input file, if the debug writer wants it. */
1438 if (debug_hooks->start_end_main_source_file)
1439 debug_hooks->end_source_file (0);
1440
1441 had_errors:
1442 /* Add the D frontend error count to the GCC error count to correctly
1443 exit with an error status. */
1444 errorcount += (global.errors + global.warnings);
1445
1446 /* We want to write the mixin expansion file also on error. */
1447 if (global.params.mixinOut.doOutput)
1448 {
1449 d_write_file (global.params.mixinOut.name.ptr,
1450 global.params.mixinOut.buffer->peekChars ());
1451 }
1452
1453 /* Remove generated .di files on error. */
1454 if (errorcount && dump_headers)
1455 {
1456 for (size_t i = 0; i < modules.length; i++)
1457 {
1458 Module *m = modules[i];
1459 if (m->filetype == FileType::dhdr
1460 || (d_option.fonly && m != Module::rootModule))
1461 continue;
1462
1463 remove (m->hdrfile.toChars ());
1464 }
1465 }
1466
1467 /* Write out globals. */
1468 d_finish_compilation (vec_safe_address (global_declarations),
1469 vec_safe_length (global_declarations));
1470 }
1471
1472 /* Implements the lang_hooks.types.type_for_mode routine for language D. */
1473
1474 static tree
1475 d_type_for_mode (machine_mode mode, int unsignedp)
1476 {
1477 if (mode == QImode)
1478 return unsignedp ? d_ubyte_type : d_byte_type;
1479
1480 if (mode == HImode)
1481 return unsignedp ? d_ushort_type : d_short_type;
1482
1483 if (mode == SImode)
1484 return unsignedp ? d_uint_type : d_int_type;
1485
1486 if (mode == DImode)
1487 return unsignedp ? d_ulong_type : d_long_type;
1488
1489 if (mode == TYPE_MODE (d_cent_type))
1490 return unsignedp ? d_ucent_type : d_cent_type;
1491
1492 if (mode == TYPE_MODE (float_type_node))
1493 return float_type_node;
1494
1495 if (mode == TYPE_MODE (double_type_node))
1496 return double_type_node;
1497
1498 if (mode == TYPE_MODE (long_double_type_node))
1499 return long_double_type_node;
1500
1501 if (mode == TYPE_MODE (build_pointer_type (char8_type_node)))
1502 return build_pointer_type (char8_type_node);
1503
1504 if (mode == TYPE_MODE (build_pointer_type (d_int_type)))
1505 return build_pointer_type (d_int_type);
1506
1507 for (int i = 0; i < NUM_INT_N_ENTS; i ++)
1508 {
1509 if (int_n_enabled_p[i] && mode == int_n_data[i].m)
1510 {
1511 if (unsignedp)
1512 return int_n_trees[i].unsigned_type;
1513 else
1514 return int_n_trees[i].signed_type;
1515 }
1516 }
1517
1518 if (COMPLEX_MODE_P (mode))
1519 {
1520 machine_mode inner_mode;
1521 tree inner_type;
1522
1523 if (mode == TYPE_MODE (complex_float_type_node))
1524 return complex_float_type_node;
1525 if (mode == TYPE_MODE (complex_double_type_node))
1526 return complex_double_type_node;
1527 if (mode == TYPE_MODE (complex_long_double_type_node))
1528 return complex_long_double_type_node;
1529
1530 inner_mode = (machine_mode) GET_MODE_INNER (mode);
1531 inner_type = d_type_for_mode (inner_mode, unsignedp);
1532 if (inner_type != NULL_TREE)
1533 return build_complex_type (inner_type);
1534 }
1535 else if (VECTOR_MODE_P (mode))
1536 {
1537 machine_mode inner_mode = (machine_mode) GET_MODE_INNER (mode);
1538 tree inner_type = d_type_for_mode (inner_mode, unsignedp);
1539 if (inner_type != NULL_TREE)
1540 return build_vector_type_for_mode (inner_type, mode);
1541 }
1542
1543 return 0;
1544 }
1545
1546 /* Implements the lang_hooks.types.type_for_size routine for language D. */
1547
1548 static tree
1549 d_type_for_size (unsigned bits, int unsignedp)
1550 {
1551 if (bits <= TYPE_PRECISION (d_byte_type))
1552 return unsignedp ? d_ubyte_type : d_byte_type;
1553
1554 if (bits <= TYPE_PRECISION (d_short_type))
1555 return unsignedp ? d_ushort_type : d_short_type;
1556
1557 if (bits <= TYPE_PRECISION (d_int_type))
1558 return unsignedp ? d_uint_type : d_int_type;
1559
1560 if (bits <= TYPE_PRECISION (d_long_type))
1561 return unsignedp ? d_ulong_type : d_long_type;
1562
1563 if (bits <= TYPE_PRECISION (d_cent_type))
1564 return unsignedp ? d_ucent_type : d_cent_type;
1565
1566 for (int i = 0; i < NUM_INT_N_ENTS; i ++)
1567 {
1568 if (int_n_enabled_p[i] && bits == int_n_data[i].bitsize)
1569 {
1570 if (unsignedp)
1571 return int_n_trees[i].unsigned_type;
1572 else
1573 return int_n_trees[i].signed_type;
1574 }
1575 }
1576
1577 return 0;
1578 }
1579
1580 /* Implements the lang_hooks.types.type_promotes_to routine for language D. */
1581
1582 static tree
1583 d_type_promotes_to (tree type)
1584 {
1585 /* Promotions are only applied on unnamed function arguments for declarations
1586 with `extern(C)' or `extern(C++)' linkage. */
1587 if (cfun && DECL_LANG_FRONTEND (cfun->decl)
1588 && DECL_LANG_FRONTEND (cfun->decl)->resolvedLinkage () != LINK::d)
1589 {
1590 /* In [type/integer-promotions], integer promotions are conversions of the
1591 following types:
1592
1593 bool int
1594 byte int
1595 ubyte int
1596 short int
1597 ushort int
1598 char int
1599 wchar int
1600 dchar uint
1601
1602 If an enum has as a base type one of the types in the left column, it
1603 is converted to the type in the right column. */
1604 if (TREE_CODE (type) == ENUMERAL_TYPE && ENUM_IS_SCOPED (type))
1605 type = TREE_TYPE (type);
1606
1607 type = TYPE_MAIN_VARIANT (type);
1608
1609 /* Check for promotions of target-defined types first. */
1610 tree promoted_type = targetm.promoted_type (type);
1611 if (promoted_type)
1612 return promoted_type;
1613
1614 if (TREE_CODE (type) == BOOLEAN_TYPE)
1615 return d_int_type;
1616
1617 if (INTEGRAL_TYPE_P (type))
1618 {
1619 if (type == d_byte_type || type == d_ubyte_type
1620 || type == d_short_type || type == d_ushort_type
1621 || type == char8_type_node || type == char16_type_node)
1622 return d_int_type;
1623
1624 if (type == char32_type_node)
1625 return d_uint_type;
1626
1627 if (TYPE_PRECISION (type) < TYPE_PRECISION (d_int_type))
1628 return d_int_type;
1629 }
1630
1631 /* Float arguments are converted to doubles. */
1632 if (type == float_type_node)
1633 return double_type_node;
1634
1635 if (type == ifloat_type_node)
1636 return idouble_type_node;
1637 }
1638
1639 return type;
1640 }
1641
1642 /* Implements the lang_hooks.decls.global_bindings_p routine for language D.
1643 Return true if we are in the global binding level. */
1644
1645 static bool
1646 d_global_bindings_p (void)
1647 {
1648 return (current_binding_level == global_binding_level);
1649 }
1650
1651 /* Return global_context, but create it first if need be. */
1652
1653 static tree
1654 get_global_context (void)
1655 {
1656 if (!global_context)
1657 {
1658 global_context = build_translation_unit_decl (NULL_TREE);
1659 debug_hooks->register_main_translation_unit (global_context);
1660 }
1661
1662 return global_context;
1663 }
1664
1665 /* Implements the lang_hooks.decls.pushdecl routine for language D.
1666 Record DECL as belonging to the current lexical scope. */
1667
1668 tree
1669 d_pushdecl (tree decl)
1670 {
1671 /* Set the context of the decl. If current_function_decl did not help in
1672 determining the context, use global scope. */
1673 if (!DECL_CONTEXT (decl))
1674 {
1675 if (current_function_decl)
1676 DECL_CONTEXT (decl) = current_function_decl;
1677 else
1678 DECL_CONTEXT (decl) = get_global_context ();
1679 }
1680
1681 /* Put decls on list in reverse order. */
1682 if (TREE_STATIC (decl) || d_global_bindings_p ())
1683 vec_safe_push (global_declarations, decl);
1684 else
1685 {
1686 TREE_CHAIN (decl) = current_binding_level->names;
1687 current_binding_level->names = decl;
1688 }
1689
1690 return decl;
1691 }
1692
1693 /* Implements the lang_hooks.decls.getdecls routine for language D.
1694 Return the list of declarations of the current level. */
1695
1696 static tree
1697 d_getdecls (void)
1698 {
1699 if (current_binding_level)
1700 return current_binding_level->names;
1701
1702 return NULL_TREE;
1703 }
1704
1705
1706 /* Implements the lang_hooks.get_alias_set routine for language D.
1707 Get the alias set corresponding to type or expression T.
1708 Return -1 if we don't do anything special. */
1709
1710 static alias_set_type
1711 d_get_alias_set (tree)
1712 {
1713 /* For now in D, assume everything aliases everything else, until we define
1714 some solid rules backed by a specification. There are also some parts
1715 of code generation routines that don't adhere to C alias rules, such as
1716 build_vconvert. In any case, a lot of user code already assumes there
1717 is no strict aliasing and will break if we were to change that. */
1718 return 0;
1719 }
1720
1721 /* Implements the lang_hooks.types_compatible_p routine for language D.
1722 Compares two types for equivalence in the D programming language.
1723 This routine should only return 1 if it is sure, even though the frontend
1724 should have already ensured that all types are compatible before handing
1725 over the parsed ASTs to the code generator. */
1726
1727 static int
1728 d_types_compatible_p (tree x, tree y)
1729 {
1730 Type *tx = TYPE_LANG_FRONTEND (x);
1731 Type *ty = TYPE_LANG_FRONTEND (y);
1732
1733 /* Try validating the types in the frontend. */
1734 if (tx != NULL && ty != NULL)
1735 {
1736 /* Types are equivalent. */
1737 if (same_type_p (tx, ty))
1738 return true;
1739
1740 /* Type system allows implicit conversion between. */
1741 if (dmd::implicitConvTo (tx, ty) != MATCH::nomatch
1742 || dmd::implicitConvTo (ty, tx) != MATCH::nomatch)
1743 return true;
1744 }
1745
1746 /* Fallback on using type flags for comparison. E.g: all dynamic arrays
1747 are distinct types in D, but are VIEW_CONVERT compatible. */
1748 if (TREE_CODE (x) == RECORD_TYPE && TREE_CODE (y) == RECORD_TYPE)
1749 {
1750 if (TYPE_DYNAMIC_ARRAY (x) && TYPE_DYNAMIC_ARRAY (y))
1751 return true;
1752
1753 if (TYPE_DELEGATE (x) && TYPE_DELEGATE (y))
1754 return true;
1755
1756 if (TYPE_ASSOCIATIVE_ARRAY (x) && TYPE_ASSOCIATIVE_ARRAY (y))
1757 return true;
1758 }
1759
1760 return false;
1761 }
1762
1763 /* Implements the lang_hooks.finish_incomplete_decl routine for language D. */
1764
1765 static void
1766 d_finish_incomplete_decl (tree decl)
1767 {
1768 if (VAR_P (decl))
1769 {
1770 /* D allows zero-length declarations. Such a declaration ends up with
1771 DECL_SIZE (t) == NULL_TREE which is what the back-end function
1772 assembler_variable checks. This could change in later versions, or
1773 maybe all of these variables should be aliased to one symbol. */
1774 if (DECL_SIZE (decl) == 0)
1775 {
1776 DECL_SIZE (decl) = bitsize_zero_node;
1777 DECL_SIZE_UNIT (decl) = size_zero_node;
1778 }
1779 }
1780 }
1781
1782 /* Implements the lang_hooks.types.classify_record routine for language D.
1783 Return the true debug type for TYPE. */
1784
1785 static classify_record
1786 d_classify_record (tree type)
1787 {
1788 Type *t = TYPE_LANG_FRONTEND (type);
1789 TypeClass *tc = t ? t->isTypeClass () : NULL;
1790
1791 if (tc != NULL)
1792 {
1793 /* extern(C++) interfaces get emitted as classes. */
1794 if (tc->sym->isInterfaceDeclaration ()
1795 && !tc->sym->isCPPinterface ())
1796 return RECORD_IS_INTERFACE;
1797
1798 return RECORD_IS_CLASS;
1799 }
1800
1801 return RECORD_IS_STRUCT;
1802 }
1803
1804 /* Implements the lang_hooks.tree_size routine for language D.
1805 Determine the size of our tcc_constant or tcc_exceptional nodes. */
1806
1807 static size_t
1808 d_tree_size (tree_code code)
1809 {
1810 switch (code)
1811 {
1812 case FUNCFRAME_INFO:
1813 return sizeof (tree_frame_info);
1814
1815 default:
1816 gcc_unreachable ();
1817 }
1818 }
1819
1820 /* Implements the lang_hooks.print_xnode routine for language D. */
1821
1822 static void
1823 d_print_xnode (FILE *file, tree node, int indent)
1824 {
1825 switch (TREE_CODE (node))
1826 {
1827 case FUNCFRAME_INFO:
1828 print_node (file, "frame_type", FRAMEINFO_TYPE (node), indent + 4);
1829 break;
1830
1831 default:
1832 break;
1833 }
1834 }
1835
1836 /* Return which tree structure is used by NODE, or TS_D_GENERIC if NODE
1837 is one of the language-independent trees. */
1838
1839 d_tree_node_structure_enum
1840 d_tree_node_structure (lang_tree_node *t)
1841 {
1842 switch (TREE_CODE (&t->generic))
1843 {
1844 case IDENTIFIER_NODE:
1845 return TS_D_IDENTIFIER;
1846
1847 case FUNCFRAME_INFO:
1848 return TS_D_FRAMEINFO;
1849
1850 default:
1851 return TS_D_GENERIC;
1852 }
1853 }
1854
1855 /* Allocate and return a lang specific structure for the frontend type. */
1856
1857 struct lang_type *
1858 build_lang_type (Type *t)
1859 {
1860 struct lang_type *lt = ggc_cleared_alloc <struct lang_type> ();
1861 lt->type = t;
1862 return lt;
1863 }
1864
1865 /* Allocate and return a lang specific structure for the frontend decl. */
1866
1867 struct lang_decl *
1868 build_lang_decl (Declaration *d)
1869 {
1870 /* For compiler generated run-time typeinfo, a lang_decl is allocated even if
1871 there's no associated frontend symbol to refer to (yet). If the symbol
1872 appears later in the compilation, then the slot will be re-used. */
1873 if (d == NULL)
1874 return ggc_cleared_alloc <struct lang_decl> ();
1875
1876 struct lang_decl *ld = (d->csym) ? DECL_LANG_SPECIFIC (d->csym) : NULL;
1877 if (ld == NULL)
1878 ld = ggc_cleared_alloc <struct lang_decl> ();
1879
1880 if (ld->decl == NULL)
1881 ld->decl = d;
1882
1883 return ld;
1884 }
1885
1886 /* Implements the lang_hooks.dup_lang_specific_decl routine for language D.
1887 Replace the DECL_LANG_SPECIFIC field of NODE with a copy. */
1888
1889 static void
1890 d_dup_lang_specific_decl (tree node)
1891 {
1892 if (!DECL_LANG_SPECIFIC (node))
1893 return;
1894
1895 struct lang_decl *ld = ggc_alloc <struct lang_decl> ();
1896 memcpy (ld, DECL_LANG_SPECIFIC (node), sizeof (struct lang_decl));
1897 DECL_LANG_SPECIFIC (node) = ld;
1898 }
1899
1900 /* This preserves trees we create from the garbage collector. */
1901
1902 static GTY(()) tree d_keep_list = NULL_TREE;
1903
1904 void
1905 d_keep (tree t)
1906 {
1907 d_keep_list = tree_cons (NULL_TREE, t, d_keep_list);
1908 }
1909
1910 /* Implements the lang_hooks.eh_personality routine for language D.
1911 Return the GDC personality function decl. */
1912
1913 static GTY(()) tree d_eh_personality_decl;
1914
1915 static tree
1916 d_eh_personality (void)
1917 {
1918 if (!d_eh_personality_decl)
1919 d_eh_personality_decl = build_personality_function ("gdc");
1920
1921 return d_eh_personality_decl;
1922 }
1923
1924 /* Implements the lang_hooks.eh_runtime_type routine for language D. */
1925
1926 static tree
1927 d_build_eh_runtime_type (tree type)
1928 {
1929 Type *t = TYPE_LANG_FRONTEND (type);
1930 gcc_assert (t != NULL);
1931 t = t->toBasetype ();
1932
1933 ClassDeclaration *cd = t->isTypeClass ()->sym;
1934 tree decl;
1935
1936 if (cd->isCPPclass ())
1937 decl = get_cpp_typeinfo_decl (cd);
1938 else
1939 decl = get_classinfo_decl (cd);
1940
1941 return convert (ptr_type_node, build_address (decl));
1942 }
1943
1944 /* Implements the lang_hooks.enum_underlying_base_type routine for language D.
1945 Returns the underlying type of the given enumeration TYPE. */
1946
1947 static tree
1948 d_enum_underlying_base_type (const_tree type)
1949 {
1950 gcc_assert (TREE_CODE (type) == ENUMERAL_TYPE);
1951 return TREE_TYPE (type);
1952 }
1953
1954 /* Get a value for the SARIF v2.1.0 "artifact.sourceLanguage" property,
1955 based on the list in SARIF v2.1.0 Appendix J. */
1956
1957 static const char *
1958 d_get_sarif_source_language (const char *)
1959 {
1960 return "d";
1961 }
1962
1963 const scoped_attribute_specs *const d_langhook_attribute_table[] =
1964 {
1965 &d_langhook_gnu_attribute_table,
1966 &d_langhook_common_attribute_table,
1967 };
1968
1969 /* Definitions for our language-specific hooks. */
1970
1971 #undef LANG_HOOKS_NAME
1972 #undef LANG_HOOKS_INIT
1973 #undef LANG_HOOKS_INIT_TS
1974 #undef LANG_HOOKS_INIT_OPTIONS
1975 #undef LANG_HOOKS_INIT_OPTIONS_STRUCT
1976 #undef LANG_HOOKS_OPTION_LANG_MASK
1977 #undef LANG_HOOKS_HANDLE_OPTION
1978 #undef LANG_HOOKS_POST_OPTIONS
1979 #undef LANG_HOOKS_PARSE_FILE
1980 #undef LANG_HOOKS_ATTRIBUTE_TABLE
1981 #undef LANG_HOOKS_GET_ALIAS_SET
1982 #undef LANG_HOOKS_TYPES_COMPATIBLE_P
1983 #undef LANG_HOOKS_BUILTIN_FUNCTION
1984 #undef LANG_HOOKS_BUILTIN_FUNCTION_EXT_SCOPE
1985 #undef LANG_HOOKS_REGISTER_BUILTIN_TYPE
1986 #undef LANG_HOOKS_FINISH_INCOMPLETE_DECL
1987 #undef LANG_HOOKS_GIMPLIFY_EXPR
1988 #undef LANG_HOOKS_CLASSIFY_RECORD
1989 #undef LANG_HOOKS_TREE_SIZE
1990 #undef LANG_HOOKS_PRINT_XNODE
1991 #undef LANG_HOOKS_DUP_LANG_SPECIFIC_DECL
1992 #undef LANG_HOOKS_EH_PERSONALITY
1993 #undef LANG_HOOKS_EH_RUNTIME_TYPE
1994 #undef LANG_HOOKS_ENUM_UNDERLYING_BASE_TYPE
1995 #undef LANG_HOOKS_PUSHDECL
1996 #undef LANG_HOOKS_GETDECLS
1997 #undef LANG_HOOKS_GLOBAL_BINDINGS_P
1998 #undef LANG_HOOKS_TYPE_FOR_MODE
1999 #undef LANG_HOOKS_TYPE_FOR_SIZE
2000 #undef LANG_HOOKS_TYPE_PROMOTES_TO
2001 #undef LANG_HOOKS_GET_SARIF_SOURCE_LANGUAGE
2002
2003 #define LANG_HOOKS_NAME "GNU D"
2004 #define LANG_HOOKS_INIT d_init
2005 #define LANG_HOOKS_INIT_TS d_init_ts
2006 #define LANG_HOOKS_INIT_OPTIONS d_init_options
2007 #define LANG_HOOKS_INIT_OPTIONS_STRUCT d_init_options_struct
2008 #define LANG_HOOKS_OPTION_LANG_MASK d_option_lang_mask
2009 #define LANG_HOOKS_HANDLE_OPTION d_handle_option
2010 #define LANG_HOOKS_POST_OPTIONS d_post_options
2011 #define LANG_HOOKS_PARSE_FILE d_parse_file
2012 #define LANG_HOOKS_ATTRIBUTE_TABLE d_langhook_attribute_table
2013 #define LANG_HOOKS_GET_ALIAS_SET d_get_alias_set
2014 #define LANG_HOOKS_TYPES_COMPATIBLE_P d_types_compatible_p
2015 #define LANG_HOOKS_BUILTIN_FUNCTION d_builtin_function
2016 #define LANG_HOOKS_BUILTIN_FUNCTION_EXT_SCOPE d_builtin_function_ext_scope
2017 #define LANG_HOOKS_REGISTER_BUILTIN_TYPE d_register_builtin_type
2018 #define LANG_HOOKS_FINISH_INCOMPLETE_DECL d_finish_incomplete_decl
2019 #define LANG_HOOKS_GIMPLIFY_EXPR d_gimplify_expr
2020 #define LANG_HOOKS_CLASSIFY_RECORD d_classify_record
2021 #define LANG_HOOKS_TREE_SIZE d_tree_size
2022 #define LANG_HOOKS_PRINT_XNODE d_print_xnode
2023 #define LANG_HOOKS_DUP_LANG_SPECIFIC_DECL d_dup_lang_specific_decl
2024 #define LANG_HOOKS_EH_PERSONALITY d_eh_personality
2025 #define LANG_HOOKS_EH_RUNTIME_TYPE d_build_eh_runtime_type
2026 #define LANG_HOOKS_ENUM_UNDERLYING_BASE_TYPE d_enum_underlying_base_type
2027 #define LANG_HOOKS_PUSHDECL d_pushdecl
2028 #define LANG_HOOKS_GETDECLS d_getdecls
2029 #define LANG_HOOKS_GLOBAL_BINDINGS_P d_global_bindings_p
2030 #define LANG_HOOKS_TYPE_FOR_MODE d_type_for_mode
2031 #define LANG_HOOKS_TYPE_FOR_SIZE d_type_for_size
2032 #define LANG_HOOKS_TYPE_PROMOTES_TO d_type_promotes_to
2033 #define LANG_HOOKS_GET_SARIF_SOURCE_LANGUAGE d_get_sarif_source_language
2034
2035 struct lang_hooks lang_hooks = LANG_HOOKS_INITIALIZER;
2036
2037 #include "gt-d-d-lang.h"
2038 #include "gtype-d.h"