1------------------------------------------------------------------------------
2--                                                                          --
3--                         GNAT COMPILER COMPONENTS                         --
4--                                                                          --
5--                             G N A T 1 D R V                              --
6--                                                                          --
7--                                 B o d y                                  --
8--                                                                          --
9--          Copyright (C) 1992-2019, Free Software Foundation, Inc.         --
10--                                                                          --
11-- GNAT is free software;  you can  redistribute it  and/or modify it under --
12-- terms of the  GNU General Public License as published  by the Free Soft- --
13-- ware  Foundation;  either version 3,  or (at your option) any later ver- --
14-- sion.  GNAT is distributed in the hope that it will be useful, but WITH- --
15-- OUT ANY WARRANTY;  without even the  implied warranty of MERCHANTABILITY --
16-- or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License --
17-- for  more details.  You should have  received  a copy of the GNU General --
18-- Public License  distributed with GNAT; see file COPYING3.  If not, go to --
19-- http://www.gnu.org/licenses for a complete copy of the license.          --
20--                                                                          --
21-- GNAT was originally developed  by the GNAT team at  New York University. --
22-- Extensive contributions were provided by Ada Core Technologies Inc.      --
23--                                                                          --
24------------------------------------------------------------------------------
25
26with Atree;     use Atree;
27with Back_End;  use Back_End;
28with Checks;
29with Comperr;
30with Csets;
31with Debug;     use Debug;
32with Elists;
33with Errout;    use Errout;
34with Exp_CG;
35with Fmap;
36with Fname;     use Fname;
37with Fname.UF;  use Fname.UF;
38with Frontend;
39with Ghost;     use Ghost;
40with Gnatvsn;   use Gnatvsn;
41with Inline;
42with Lib;       use Lib;
43with Lib.Writ;  use Lib.Writ;
44with Lib.Xref;
45with Namet;     use Namet;
46with Nlists;
47with Opt;       use Opt;
48with Osint;     use Osint;
49with Osint.C;   use Osint.C;
50with Output;    use Output;
51with Par_SCO;
52with Prepcomp;
53with Repinfo;
54with Restrict;
55with Rident;    use Rident;
56with Rtsfind;
57with SCOs;
58with Sem;
59with Sem_Ch8;
60with Sem_Ch12;
61with Sem_Ch13;
62with Sem_Elim;
63with Sem_Eval;
64with Sem_SPARK; use Sem_SPARK;
65with Sem_Type;
66with Set_Targ;
67with Sinfo;     use Sinfo;
68with Sinput.L;  use Sinput.L;
69with Snames;    use Snames;
70with Sprint;    use Sprint;
71with Stringt;
72with Stylesw;   use Stylesw;
73with Targparm;  use Targparm;
74with Tbuild;
75with Tree_Gen;
76with Treepr;    use Treepr;
77with Ttypes;
78with Types;     use Types;
79with Uintp;
80with Uname;     use Uname;
81with Urealp;
82with Usage;
83with Validsw;   use Validsw;
84
85with System.Assertions;
86with System.OS_Lib;
87
88--------------
89-- Gnat1drv --
90--------------
91
92procedure Gnat1drv is
93   procedure Adjust_Global_Switches;
94   --  There are various interactions between front-end switch settings,
95   --  including debug switch settings and target dependent parameters.
96   --  This procedure takes care of properly handling these interactions.
97   --  We do it after scanning out all the switches, so that we are not
98   --  depending on the order in which switches appear.
99
100   procedure Check_Bad_Body (Unit_Node : Node_Id; Unit_Kind : Node_Kind);
101   --  Called to check whether a unit described by its compilation unit node
102   --  and kind has a bad body.
103
104   procedure Check_Rep_Info;
105   --  Called when we are not generating code, to check if -gnatR was requested
106   --  and if so, explain that we will not be honoring the request.
107
108   procedure Post_Compilation_Validation_Checks;
109   --  This procedure performs various validation checks that have to be left
110   --  to the end of the compilation process, after generating code but before
111   --  issuing error messages. In particular, these checks generally require
112   --  the information provided by the back end in back annotation of declared
113   --  entities (e.g. actual size and alignment values chosen by the back end).
114
115   ----------------------------
116   -- Adjust_Global_Switches --
117   ----------------------------
118
119   procedure Adjust_Global_Switches is
120      procedure SPARK_Library_Warning (Kind : String);
121      --  Issue a warning in GNATprove mode if the run-time library does not
122      --  fully support IEEE-754 floating-point semantics.
123
124      ---------------------------
125      -- SPARK_Library_Warning --
126      ---------------------------
127
128      procedure SPARK_Library_Warning (Kind : String) is
129      begin
130         Write_Line
131           ("warning: run-time library may be configured incorrectly");
132         Write_Line
133           ("warning: (SPARK analysis requires support for " & Kind & ')');
134      end SPARK_Library_Warning;
135
136   --  Start of processing for Adjust_Global_Switches
137
138   begin
139      --  Define pragma GNAT_Annotate as an alias of pragma Annotate, to be
140      --  able to work around bootstrap limitations with the old syntax of
141      --  pragma Annotate, and use pragma GNAT_Annotate in compiler sources
142      --  when needed.
143
144      Map_Pragma_Name (From => Name_Gnat_Annotate, To => Name_Annotate);
145
146      --  -gnatd.M enables Relaxed_RM_Semantics
147
148      if Debug_Flag_Dot_MM then
149         Relaxed_RM_Semantics := True;
150      end if;
151
152      --  -gnatd.1 enables unnesting of subprograms
153
154      if Debug_Flag_Dot_1 then
155         Unnest_Subprogram_Mode := True;
156      end if;
157
158      --  -gnatd.u enables special C expansion mode
159
160      if Debug_Flag_Dot_U then
161         Modify_Tree_For_C := True;
162      end if;
163
164      --  -gnatd_A disables generation of ALI files
165
166      if Debug_Flag_Underscore_AA then
167         Disable_ALI_File := True;
168      end if;
169
170      --  Set all flags required when generating C code
171
172      if Generate_C_Code then
173         Modify_Tree_For_C := True;
174         Unnest_Subprogram_Mode := True;
175         Building_Static_Dispatch_Tables := False;
176         Minimize_Expression_With_Actions := True;
177         Expand_Nonbinary_Modular_Ops := True;
178
179         --  Set operating mode to Generate_Code to benefit from full front-end
180         --  expansion (e.g. generics).
181
182         Operating_Mode := Generate_Code;
183
184         --  Suppress alignment checks since we do not have access to alignment
185         --  info on the target.
186
187         Suppress_Options.Suppress (Alignment_Check) := False;
188      end if;
189
190      --  -gnatd.E sets Error_To_Warning mode, causing selected error messages
191      --  to be treated as warnings instead of errors.
192
193      if Debug_Flag_Dot_EE then
194         Error_To_Warning := True;
195      end if;
196
197      --  -gnatdJ sets Include_Subprogram_In_Messages, adding the related
198      --  subprogram as part of the error and warning messages.
199
200      if Debug_Flag_JJ then
201         Include_Subprogram_In_Messages := True;
202      end if;
203
204      --  Disable CodePeer_Mode in Check_Syntax, since we need front-end
205      --  expansion.
206
207      if Operating_Mode = Check_Syntax then
208         CodePeer_Mode := False;
209      end if;
210
211      --  Set ASIS mode if -gnatt and -gnatc are set
212
213      if Operating_Mode = Check_Semantics and then Tree_Output then
214         ASIS_Mode := True;
215
216         --  Set ASIS GNSA mode if -gnatd.H is set
217
218         if Debug_Flag_Dot_HH then
219            ASIS_GNSA_Mode := True;
220         end if;
221
222         --  Turn off inlining in ASIS mode, since ASIS cannot handle the extra
223         --  information in the trees caused by inlining being active.
224
225         --  More specifically, the tree seems to be malformed from the ASIS
226         --  point of view if -gnatc and -gnatn appear together???
227
228         Inline_Active := False;
229
230         --  Turn off SCIL generation and CodePeer mode in semantics mode,
231         --  since SCIL requires front-end expansion.
232
233         Generate_SCIL := False;
234         CodePeer_Mode := False;
235      end if;
236
237      --  SCIL mode needs to disable front-end inlining since the generated
238      --  trees (in particular order and consistency between specs compiled
239      --  as part of a main unit or as part of a with-clause) are causing
240      --  troubles.
241
242      if Generate_SCIL then
243         Front_End_Inlining := False;
244      end if;
245
246      --  Tune settings for optimal SCIL generation in CodePeer mode
247
248      if CodePeer_Mode then
249
250         --  Turn off gnatprove mode (which can be set via e.g. -gnatd.F), not
251         --  compatible with CodePeer mode.
252
253         GNATprove_Mode := False;
254         Debug_Flag_Dot_FF := False;
255
256         --  Turn off length expansion. CodePeer has its own mechanism to
257         --  handle length attribute.
258
259         Debug_Flag_Dot_PP := True;
260
261         --  Turn off C tree generation, not compatible with CodePeer mode. We
262         --  do not expect this to happen in normal use, since both modes are
263         --  enabled by special tools, but it is useful to turn off these flags
264         --  this way when we are doing CodePeer tests on existing test suites
265         --  that may have -gnateg set, to avoid the need for special casing.
266
267         Modify_Tree_For_C      := False;
268         Generate_C_Code        := False;
269         Unnest_Subprogram_Mode := False;
270
271         --  Turn off inlining, confuses CodePeer output and gains nothing
272
273         Front_End_Inlining := False;
274         Inline_Active      := False;
275
276         --  Disable front-end optimizations, to keep the tree as close to the
277         --  source code as possible, and also to avoid inconsistencies between
278         --  trees when using different optimization switches.
279
280         Optimization_Level := 0;
281
282         --  Enable some restrictions systematically to simplify the generated
283         --  code (and ease analysis). Note that restriction checks are also
284         --  disabled in CodePeer mode, see Restrict.Check_Restriction, and
285         --  user specified Restrictions pragmas are ignored, see
286         --  Sem_Prag.Process_Restrictions_Or_Restriction_Warnings.
287
288         Restrict.Restrictions.Set   (No_Exception_Registration)       := True;
289         Restrict.Restrictions.Set   (No_Initialize_Scalars)           := True;
290         Restrict.Restrictions.Set   (No_Task_Hierarchy)               := True;
291         Restrict.Restrictions.Set   (No_Abort_Statements)             := True;
292         Restrict.Restrictions.Set   (Max_Asynchronous_Select_Nesting) := True;
293         Restrict.Restrictions.Value (Max_Asynchronous_Select_Nesting) := 0;
294
295         --  Enable pragma Ignore_Pragma (Global) to support legacy code. As a
296         --  consequence, Refined_Global pragma should be ignored as well, as
297         --  it is only allowed on a body when pragma Global is given for the
298         --  spec.
299
300         Set_Name_Table_Boolean3 (Name_Global, True);
301         Set_Name_Table_Boolean3 (Name_Refined_Global, True);
302
303         --  Suppress division by zero checks since they are handled
304         --  implicitly by CodePeer.
305
306         --  Turn off dynamic elaboration checks: generates inconsistencies in
307         --  trees between specs compiled as part of a main unit or as part of
308         --  a with-clause.
309
310         --  Turn off alignment checks: these cannot be proved statically by
311         --  CodePeer and generate false positives.
312
313         --  Enable all other language checks
314
315         Suppress_Options.Suppress :=
316           (Alignment_Check   => True,
317            Division_Check    => True,
318            Elaboration_Check => True,
319            others            => False);
320
321         Dynamic_Elaboration_Checks := False;
322
323         --  Set STRICT mode for overflow checks if not set explicitly. This
324         --  prevents suppressing of overflow checks by default, in code down
325         --  below.
326
327         if Suppress_Options.Overflow_Mode_General = Not_Set then
328            Suppress_Options.Overflow_Mode_General    := Strict;
329            Suppress_Options.Overflow_Mode_Assertions := Strict;
330         end if;
331
332         --  CodePeer handles division and overflow checks directly, based on
333         --  the marks set by the frontend, hence no special expansion should
334         --  be performed in the frontend for division and overflow checks.
335
336         Backend_Divide_Checks_On_Target   := True;
337         Backend_Overflow_Checks_On_Target := True;
338
339         --  Kill debug of generated code, since it messes up sloc values
340
341         Debug_Generated_Code := False;
342
343         --  Ditto for -gnateG which interacts badly with handling of pragma
344         --  Annotate in gnat2scil.
345
346         Generate_Processed_File := False;
347
348         --  Disable Exception_Extra_Info (-gnateE) which generates more
349         --  complex trees with no added value, and may confuse CodePeer.
350
351         Exception_Extra_Info := False;
352
353         --  Turn cross-referencing on in case it was disabled (e.g. by -gnatD)
354         --  to support source navigation.
355
356         Xref_Active := True;
357
358         --  Polling mode forced off, since it generates confusing junk
359
360         Polling_Required := False;
361
362         --  Set operating mode to Generate_Code to benefit from full front-end
363         --  expansion (e.g. generics).
364
365         Operating_Mode := Generate_Code;
366
367         --  We need SCIL generation of course
368
369         Generate_SCIL := True;
370
371         --  Enable assertions, since they give CodePeer valuable extra info
372
373         Assertions_Enabled := True;
374
375         --  Set normal RM validity checking and checking of copies (to catch
376         --  e.g. wrong values used in unchecked conversions).
377         --  All other validity checking is turned off, since this can generate
378         --  very complex trees that only confuse CodePeer and do not bring
379         --  enough useful info.
380
381         Reset_Validity_Check_Options;
382         Validity_Check_Default       := True;
383         Validity_Check_Copies        := True;
384         Check_Validity_Of_Parameters := False;
385
386         --  Turn off style check options and ignore any style check pragmas
387         --  since we are not interested in any front-end warnings when we are
388         --  getting CodePeer output.
389
390         Reset_Style_Check_Options;
391         Ignore_Style_Checks_Pragmas := True;
392
393         --  Always perform semantics and generate ali files in CodePeer mode,
394         --  so that a gnatmake -c -k will proceed further when possible.
395
396         Force_ALI_Tree_File := True;
397         Try_Semantics := True;
398
399         --  Make the Ada front end more liberal so that the compiler will
400         --  allow illegal code that is allowed by other compilers. CodePeer
401         --  is in the business of finding problems, not enforcing rules.
402         --  This is useful when using CodePeer mode with other compilers.
403
404         Relaxed_RM_Semantics := True;
405
406         if not Generate_CodePeer_Messages then
407
408            --  Suppress compiler warnings by default when generating SCIL for
409            --  CodePeer, except when combined with -gnateC where we do want to
410            --  emit GNAT warnings.
411
412            Warning_Mode := Suppress;
413         end if;
414
415         --  Disable all simple value propagation. This is an optimization
416         --  which is valuable for code optimization, and also for generation
417         --  of compiler warnings, but these are being turned off by default,
418         --  and CodePeer generates better messages (referencing original
419         --  variables) this way.
420         --  Do this only if -gnatws is set (the default with -gnatcC), so that
421         --  if warnings are enabled, we'll get better messages from GNAT.
422
423         if Warning_Mode = Suppress then
424            Debug_Flag_MM := True;
425         end if;
426      end if;
427
428      --  Enable some individual switches that are implied by relaxed RM
429      --  semantics mode.
430
431      if Relaxed_RM_Semantics then
432         Opt.Allow_Integer_Address := True;
433         Overriding_Renamings := True;
434         Treat_Categorization_Errors_As_Warnings := True;
435      end if;
436
437      --  Enable GNATprove_Mode when using -gnatd.F switch
438
439      if Debug_Flag_Dot_FF then
440         GNATprove_Mode := True;
441      end if;
442
443      --  GNATprove_Mode is also activated by default in the gnat2why
444      --  executable.
445
446      if GNATprove_Mode then
447
448         --  Turn off CodePeer mode (which can be set via e.g. -gnatC or
449         --  -gnateC), not compatible with GNATprove mode.
450
451         CodePeer_Mode := False;
452         Generate_SCIL := False;
453
454         --  Turn off C tree generation, not compatible with GNATprove mode. We
455         --  do not expect this to happen in normal use, since both modes are
456         --  enabled by special tools, but it is useful to turn off these flags
457         --  this way when we are doing GNATprove tests on existing test suites
458         --  that may have -gnateg set, to avoid the need for special casing.
459
460         Modify_Tree_For_C := False;
461         Generate_C_Code := False;
462         Unnest_Subprogram_Mode := False;
463
464         --  Turn off inlining, which would confuse formal verification output
465         --  and gain nothing.
466
467         Front_End_Inlining := False;
468         Inline_Active      := False;
469
470         --  Issue warnings for failure to inline subprograms, as otherwise
471         --  expected in GNATprove mode for the local subprograms without
472         --  contracts.
473
474         Ineffective_Inline_Warnings := True;
475
476         --  Do not issue warnings for possible propagation of exception.
477         --  GNATprove already issues messages about possible exceptions.
478
479         No_Warn_On_Non_Local_Exception := True;
480         Warn_On_Non_Local_Exception := False;
481
482         --  Disable front-end optimizations, to keep the tree as close to the
483         --  source code as possible, and also to avoid inconsistencies between
484         --  trees when using different optimization switches.
485
486         Optimization_Level := 0;
487
488         --  Enable some restrictions systematically to simplify the generated
489         --  code (and ease analysis).
490
491         Restrict.Restrictions.Set (No_Initialize_Scalars) := True;
492
493         --  Note: at this point we used to suppress various checks, but that
494         --  is not what we want. We need the semantic processing for these
495         --  checks (which will set flags like Do_Overflow_Check, showing the
496         --  points at which potential checks are required semantically). We
497         --  don't want the expansion associated with these checks, but that
498         --  happens anyway because this expansion is simply not done in the
499         --  SPARK version of the expander.
500
501         --  On the contrary, we need to enable explicitly all language checks,
502         --  as they may have been suppressed by the use of switch -gnatp.
503
504         Suppress_Options.Suppress := (others => False);
505
506         --  Detect overflow on unconstrained floating-point types, such as
507         --  the predefined types Float, Long_Float and Long_Long_Float from
508         --  package Standard. Not necessary if float overflows are checked
509         --  (Machine_Overflow true), since appropriate Do_Overflow_Check flags
510         --  will be set in any case.
511
512         Check_Float_Overflow := not Machine_Overflows_On_Target;
513
514         --  Set STRICT mode for overflow checks if not set explicitly. This
515         --  prevents suppressing of overflow checks by default, in code down
516         --  below.
517
518         if Suppress_Options.Overflow_Mode_General = Not_Set then
519            Suppress_Options.Overflow_Mode_General    := Strict;
520            Suppress_Options.Overflow_Mode_Assertions := Strict;
521         end if;
522
523         --  Kill debug of generated code, since it messes up sloc values
524
525         Debug_Generated_Code := False;
526
527         --  Turn cross-referencing on in case it was disabled (e.g. by -gnatD)
528         --  as it is needed for computing effects of subprograms in the formal
529         --  verification backend.
530
531         Xref_Active := True;
532
533         --  Polling mode forced off, since it generates confusing junk
534
535         Polling_Required := False;
536
537         --  Set operating mode to Check_Semantics, but a light front-end
538         --  expansion is still performed.
539
540         Operating_Mode := Check_Semantics;
541
542         --  Enable assertions, since they give valuable extra information for
543         --  formal verification.
544
545         Assertions_Enabled := True;
546
547         --  Disable validity checks, since it generates code raising
548         --  exceptions for invalid data, which confuses GNATprove. Invalid
549         --  data is directly detected by GNATprove's flow analysis.
550
551         Validity_Checks_On := False;
552         Check_Validity_Of_Parameters := False;
553
554         --  Turn off style check options since we are not interested in any
555         --  front-end warnings when we are getting SPARK output.
556
557         Reset_Style_Check_Options;
558
559         --  Suppress the generation of name tables for enumerations, which are
560         --  not needed for formal verification, and fall outside the SPARK
561         --  subset (use of pointers).
562
563         Global_Discard_Names := True;
564
565         --  Suppress the expansion of tagged types and dispatching calls,
566         --  which lead to the generation of non-SPARK code (use of pointers),
567         --  which is more complex to formally verify than the original source.
568
569         Tagged_Type_Expansion := False;
570
571         --  Detect that the runtime library support for floating-point numbers
572         --  may not be compatible with SPARK analysis of IEEE-754 floats.
573
574         if Denorm_On_Target = False then
575            SPARK_Library_Warning ("float subnormals");
576
577         elsif Machine_Rounds_On_Target = False then
578            SPARK_Library_Warning ("float rounding");
579
580         elsif Signed_Zeros_On_Target = False then
581            SPARK_Library_Warning ("signed zeros");
582         end if;
583      end if;
584
585      --  Set Configurable_Run_Time mode if system.ads flag set or if the
586      --  special debug flag -gnatdY is set.
587
588      if Targparm.Configurable_Run_Time_On_Target or Debug_Flag_YY then
589         Configurable_Run_Time_Mode := True;
590      end if;
591
592      --  Set -gnatRm mode if debug flag A set
593
594      if Debug_Flag_AA then
595         Back_Annotate_Rep_Info := True;
596         List_Representation_Info := 1;
597         List_Representation_Info_Mechanisms := True;
598      end if;
599
600      --  Force Target_Strict_Alignment true if debug flag -gnatd.a is set
601
602      if Debug_Flag_Dot_A then
603         Ttypes.Target_Strict_Alignment := True;
604      end if;
605
606      --  Increase size of allocated entities if debug flag -gnatd.N is set
607
608      if Debug_Flag_Dot_NN then
609         Atree.Num_Extension_Nodes := Atree.Num_Extension_Nodes + 1;
610      end if;
611
612      --  Disable static allocation of dispatch tables if -gnatd.t is enabled.
613      --  The front end's layout phase currently treats types that have
614      --  discriminant-dependent arrays as not being static even when a
615      --  discriminant constraint on the type is static, and this leads to
616      --  problems with subtypes of type Ada.Tags.Dispatch_Table_Wrapper. ???
617
618      if Debug_Flag_Dot_T then
619         Building_Static_Dispatch_Tables := False;
620      end if;
621
622      --  Flip endian mode if -gnatd8 set
623
624      if Debug_Flag_8 then
625         Ttypes.Bytes_Big_Endian := not Ttypes.Bytes_Big_Endian;
626      end if;
627
628      --  Set and check exception mechanism. This is only meaningful when
629      --  compiling, and in particular not meaningful for special modes used
630      --  for program analysis rather than compilation: ASIS mode, CodePeer
631      --  mode and GNATprove mode.
632
633      if Operating_Mode = Generate_Code
634        and then not (ASIS_Mode or CodePeer_Mode or GNATprove_Mode)
635      then
636         case Targparm.Frontend_Exceptions_On_Target is
637            when True =>
638               case Targparm.ZCX_By_Default_On_Target is
639                  when True =>
640                     Write_Line
641                       ("Run-time library configured incorrectly");
642                     Write_Line
643                       ("(requesting support for Frontend ZCX exceptions)");
644                     raise Unrecoverable_Error;
645
646                  when False =>
647                     Exception_Mechanism := Front_End_SJLJ;
648               end case;
649
650            when False =>
651               case Targparm.ZCX_By_Default_On_Target is
652                  when True =>
653                     Exception_Mechanism := Back_End_ZCX;
654                  when False =>
655                     Exception_Mechanism := Back_End_SJLJ;
656               end case;
657         end case;
658      end if;
659
660      --  Set proper status for overflow check mechanism
661
662      --  If already set (by -gnato or above in SPARK or CodePeer mode) then we
663      --  have nothing to do.
664
665      if Opt.Suppress_Options.Overflow_Mode_General /= Not_Set then
666         null;
667
668      --  Otherwise set overflow mode defaults
669
670      else
671         --  Overflow checks are on by default (Suppress set False) except in
672         --  GNAT_Mode, where we want them off by default (we are not ready to
673         --  enable overflow checks in the compiler yet, for one thing the case
674         --  of 64-bit checks needs System.Arith_64 which is not a compiler
675         --  unit and it is a pain to try to include it in the compiler.
676
677         Suppress_Options.Suppress (Overflow_Check) := GNAT_Mode;
678
679         --  Set appropriate default overflow handling mode. Note: at present
680         --  we set STRICT in all three of the following cases. They are
681         --  separated because in the future we may make different choices.
682
683         --  By default set STRICT mode if -gnatg in effect
684
685         if GNAT_Mode then
686            Suppress_Options.Overflow_Mode_General    := Strict;
687            Suppress_Options.Overflow_Mode_Assertions := Strict;
688
689         --  If we have backend divide and overflow checks, then by default
690         --  overflow checks are STRICT. Historically this code used to also
691         --  activate overflow checks, although no target currently has these
692         --  flags set, so this was dead code anyway.
693
694         elsif Targparm.Backend_Divide_Checks_On_Target
695                 and
696               Targparm.Backend_Overflow_Checks_On_Target
697         then
698            Suppress_Options.Overflow_Mode_General    := Strict;
699            Suppress_Options.Overflow_Mode_Assertions := Strict;
700
701         --  Otherwise for now, default is STRICT mode. This may change in the
702         --  future, but for now this is the compatible behavior with previous
703         --  versions of GNAT.
704
705         else
706            Suppress_Options.Overflow_Mode_General    := Strict;
707            Suppress_Options.Overflow_Mode_Assertions := Strict;
708         end if;
709      end if;
710
711      --  Set default for atomic synchronization. As this synchronization
712      --  between atomic accesses can be expensive, and not typically needed
713      --  on some targets, an optional target parameter can turn the option
714      --  off. Note Atomic Synchronization is implemented as check.
715
716      Suppress_Options.Suppress (Atomic_Synchronization) :=
717        not Atomic_Sync_Default_On_Target;
718
719      --  Set default for Alignment_Check, if we are on a machine with non-
720      --  strict alignment, then we suppress this check, since it is over-
721      --  zealous for such machines.
722
723      if not Ttypes.Target_Strict_Alignment then
724         Suppress_Options.Suppress (Alignment_Check) := True;
725      end if;
726
727      --  Set switch indicating if back end can handle limited types, and
728      --  guarantee that no incorrect copies are made (e.g. in the context
729      --  of an if or case expression).
730
731      --  Debug flag -gnatd.L decisively sets usage on
732
733      if Debug_Flag_Dot_LL then
734         Back_End_Handles_Limited_Types := True;
735
736      --  If no debug flag, usage off for SCIL cases
737
738      elsif Generate_SCIL then
739         Back_End_Handles_Limited_Types := False;
740
741      --  Otherwise normal gcc back end, for now still turn flag off by
742      --  default, since there are unresolved problems in the front end.
743
744      else
745         Back_End_Handles_Limited_Types := False;
746      end if;
747
748      --  If the inlining level has not been set by the user, compute it from
749      --  the optimization level: 1 at -O1/-O2 (and -Os), 2 at -O3 and above.
750
751      if Inline_Level = 0 then
752         if Optimization_Level < 3 then
753            Inline_Level := 1;
754         else
755            Inline_Level := 2;
756         end if;
757      end if;
758
759      --  Treat -gnatn as equivalent to -gnatN for non-GCC targets
760
761      if Inline_Active and not Front_End_Inlining then
762
763         --  We really should have a tag for this, what if we added a new
764         --  back end some day, it would not be true for this test, but it
765         --  would be non-GCC, so this is a bit troublesome ???
766
767         Front_End_Inlining := Generate_C_Code;
768      end if;
769
770      --  Set back-end inlining indication
771
772      Back_End_Inlining :=
773
774        --  No back-end inlining available on C generation
775
776        not Generate_C_Code
777
778        --  No back-end inlining in GNATprove mode, since it just confuses
779        --  the formal verification process.
780
781        and then not GNATprove_Mode
782
783        --  No back-end inlining if front-end inlining explicitly enabled.
784        --  Done to minimize the output differences to customers still using
785        --  this deprecated switch; in addition, this behavior reduces the
786        --  output differences in old tests.
787
788        and then not Front_End_Inlining
789
790        --  Back-end inlining is disabled if debug flag .z is set
791
792        and then not Debug_Flag_Dot_Z;
793
794      --  Output warning if -gnateE specified and cannot be supported
795
796      if Exception_Extra_Info
797        and then Restrict.No_Exception_Handlers_Set
798      then
799         Set_Standard_Error;
800         Write_Str
801           ("warning: extra exception information (-gnateE) was specified");
802         Write_Eol;
803         Write_Str
804           ("warning: this capability is not available in this configuration");
805         Write_Eol;
806         Set_Standard_Output;
807      end if;
808
809      --  Finally capture adjusted value of Suppress_Options as the initial
810      --  value for Scope_Suppress, which will be modified as we move from
811      --  scope to scope (by Suppress/Unsuppress/Overflow_Checks pragmas).
812
813      Sem.Scope_Suppress := Opt.Suppress_Options;
814   end Adjust_Global_Switches;
815
816   --------------------
817   -- Check_Bad_Body --
818   --------------------
819
820   procedure Check_Bad_Body (Unit_Node : Node_Id; Unit_Kind : Node_Kind) is
821      Fname : File_Name_Type;
822
823      procedure Bad_Body_Error (Msg : String);
824      --  Issue message for bad body found
825
826      --------------------
827      -- Bad_Body_Error --
828      --------------------
829
830      procedure Bad_Body_Error (Msg : String) is
831      begin
832         Error_Msg_N (Msg, Unit_Node);
833         Error_Msg_File_1 := Fname;
834         Error_Msg_N ("remove incorrect body in file{!", Unit_Node);
835      end Bad_Body_Error;
836
837      --  Local variables
838
839      Sname   : Unit_Name_Type;
840      Src_Ind : Source_File_Index;
841
842   --  Start of processing for Check_Bad_Body
843
844   begin
845      --  Nothing to do if we are only checking syntax, because we don't know
846      --  enough to know if we require or forbid a body in this case.
847
848      if Operating_Mode = Check_Syntax then
849         return;
850      end if;
851
852      --  Check for body not allowed
853
854      if (Unit_Kind = N_Package_Declaration
855           and then not Body_Required (Unit_Node))
856        or else (Unit_Kind = N_Generic_Package_Declaration
857                  and then not Body_Required (Unit_Node))
858        or else Unit_Kind = N_Package_Renaming_Declaration
859        or else Unit_Kind = N_Subprogram_Renaming_Declaration
860        or else Nkind (Original_Node (Unit (Unit_Node)))
861                         in N_Generic_Instantiation
862      then
863         Sname := Unit_Name (Main_Unit);
864
865         --  If we do not already have a body name, then get the body name
866
867         if not Is_Body_Name (Sname) then
868            Sname := Get_Body_Name (Sname);
869         end if;
870
871         Fname := Get_File_Name (Sname, Subunit => False);
872         Src_Ind := Load_Source_File (Fname);
873
874         --  Case where body is present and it is not a subunit. Exclude the
875         --  subunit case, because it has nothing to do with the package we are
876         --  compiling. It is illegal for a child unit and a subunit with the
877         --  same expanded name (RM 10.2(9)) to appear together in a partition,
878         --  but there is nothing to stop a compilation environment from having
879         --  both, and the test here simply allows that. If there is an attempt
880         --  to include both in a partition, this is diagnosed at bind time. In
881         --  Ada 83 mode this is not a warning case.
882
883         --  Note that in general we do not give the message if the file in
884         --  question does not look like a body. This includes weird cases,
885         --  but in particular means that if the file is just a No_Body pragma,
886         --  then we won't give the message (that's the whole point of this
887         --  pragma, to be used this way and to cause the body file to be
888         --  ignored in this context).
889
890         if Src_Ind > No_Source_File
891           and then Source_File_Is_Body (Src_Ind)
892         then
893            Errout.Finalize (Last_Call => False);
894
895            Error_Msg_Unit_1 := Sname;
896
897            --  Ada 83 case of a package body being ignored. This is not an
898            --  error as far as the Ada 83 RM is concerned, but it is almost
899            --  certainly not what is wanted so output a warning. Give this
900            --  message only if there were no errors, since otherwise it may
901            --  be incorrect (we may have misinterpreted a junk spec as not
902            --  needing a body when it really does).
903
904            if Unit_Kind = N_Package_Declaration
905              and then Ada_Version = Ada_83
906              and then Operating_Mode = Generate_Code
907              and then Distribution_Stub_Mode /= Generate_Caller_Stub_Body
908              and then not Compilation_Errors
909            then
910               Error_Msg_N
911                 ("package $$ does not require a body??", Unit_Node);
912               Error_Msg_File_1 := Fname;
913               Error_Msg_N ("body in file{ will be ignored??", Unit_Node);
914
915               --  Ada 95 cases of a body file present when no body is
916               --  permitted. This we consider to be an error.
917
918            else
919               --  For generic instantiations, we never allow a body
920
921               if Nkind (Original_Node (Unit (Unit_Node))) in
922                                                    N_Generic_Instantiation
923               then
924                  Bad_Body_Error
925                    ("generic instantiation for $$ does not allow a body");
926
927               --  A library unit that is a renaming never allows a body
928
929               elsif Unit_Kind in N_Renaming_Declaration then
930                  Bad_Body_Error
931                    ("renaming declaration for $$ does not allow a body!");
932
933                  --  Remaining cases are packages and generic packages. Here
934                  --  we only do the test if there are no previous errors,
935                  --  because if there are errors, they may lead us to
936                  --  incorrectly believe that a package does not allow a
937                  --  body when in fact it does.
938
939               elsif not Compilation_Errors then
940                  if Unit_Kind = N_Package_Declaration then
941                     Bad_Body_Error
942                       ("package $$ does not allow a body!");
943
944                  elsif Unit_Kind = N_Generic_Package_Declaration then
945                     Bad_Body_Error
946                       ("generic package $$ does not allow a body!");
947                  end if;
948               end if;
949
950            end if;
951         end if;
952      end if;
953   end Check_Bad_Body;
954
955   --------------------
956   -- Check_Rep_Info --
957   --------------------
958
959   procedure Check_Rep_Info is
960   begin
961      if List_Representation_Info /= 0
962        or else List_Representation_Info_Mechanisms
963      then
964         Set_Standard_Error;
965         Write_Eol;
966         Write_Str
967           ("cannot generate representation information, no code generated");
968         Write_Eol;
969         Write_Eol;
970         Set_Standard_Output;
971      end if;
972   end Check_Rep_Info;
973
974   ----------------------------------------
975   -- Post_Compilation_Validation_Checks --
976   ----------------------------------------
977
978   procedure Post_Compilation_Validation_Checks is
979   begin
980      --  Validate alignment check warnings. In some cases we generate warnings
981      --  about possible alignment errors because we don't know the alignment
982      --  that will be chosen by the back end. This routine is in charge of
983      --  getting rid of those warnings if we can tell they are not needed.
984
985      Checks.Validate_Alignment_Check_Warnings;
986
987      --  Validate compile time warnings and errors (using the values for size
988      --  and alignment annotated by the backend where possible). We need to
989      --  unlock temporarily these tables to reanalyze their expression.
990
991      Atree.Unlock;
992      Nlists.Unlock;
993      Sem.Unlock;
994      Sem_Ch13.Validate_Compile_Time_Warning_Errors;
995      Sem.Lock;
996      Nlists.Lock;
997      Atree.Lock;
998
999      --  Validate unchecked conversions (using the values for size and
1000      --  alignment annotated by the backend where possible).
1001
1002      Sem_Ch13.Validate_Unchecked_Conversions;
1003
1004      --  Validate address clauses (again using alignment values annotated
1005      --  by the backend where possible).
1006
1007      Sem_Ch13.Validate_Address_Clauses;
1008
1009      --  Validate independence pragmas (again using values annotated by the
1010      --  back end for component layout where possible) but only for non-GCC
1011      --  back ends, as this is done a priori for GCC back ends.
1012      --  ??? We use to test for AAMP_On_Target which is now gone, consider
1013      --
1014      --  if AAMP_On_Target then
1015      --     Sem_Ch13.Validate_Independence;
1016      --  end if;
1017   end Post_Compilation_Validation_Checks;
1018
1019   --  Local variables
1020
1021   Back_End_Mode : Back_End.Back_End_Mode_Type;
1022   Ecode         : Exit_Code_Type;
1023
1024   Main_Unit_Kind : Node_Kind;
1025   --  Kind of main compilation unit node
1026
1027   Main_Unit_Node : Node_Id;
1028   --  Compilation unit node for main unit
1029
1030--  Start of processing for Gnat1drv
1031
1032begin
1033   --  This inner block is set up to catch assertion errors and constraint
1034   --  errors. Since the code for handling these errors can cause another
1035   --  exception to be raised (namely Unrecoverable_Error), we need two
1036   --  nested blocks, so that the outer one handles unrecoverable error.
1037
1038   begin
1039      --  Initialize all packages. For the most part, these initialization
1040      --  calls can be made in any order. Exceptions are as follows:
1041
1042      --  Lib.Initialize need to be called before Scan_Compiler_Arguments,
1043      --  because it initializes a table filled by Scan_Compiler_Arguments.
1044
1045      Osint.Initialize;
1046      Fmap.Reset_Tables;
1047      Lib.Initialize;
1048      Lib.Xref.Initialize;
1049      Scan_Compiler_Arguments;
1050      Osint.Add_Default_Search_Dirs;
1051      Atree.Initialize;
1052      Nlists.Initialize;
1053      Sinput.Initialize;
1054      Sem.Initialize;
1055      Exp_CG.Initialize;
1056      Csets.Initialize;
1057      Uintp.Initialize;
1058      Urealp.Initialize;
1059      Errout.Initialize;
1060      SCOs.Initialize;
1061      Snames.Initialize;
1062      Stringt.Initialize;
1063      Ghost.Initialize;
1064      Inline.Initialize;
1065      Par_SCO.Initialize;
1066      Sem_Ch8.Initialize;
1067      Sem_Ch12.Initialize;
1068      Sem_Ch13.Initialize;
1069      Sem_Elim.Initialize;
1070      Sem_Eval.Initialize;
1071      Sem_Type.Init_Interp_Tables;
1072
1073      --  Capture compilation date and time
1074
1075      Opt.Compilation_Time := System.OS_Lib.Current_Time_String;
1076
1077      --  Get the target parameters only when -gnats is not used, to avoid
1078      --  failing when there is no default runtime.
1079
1080      if Operating_Mode /= Check_Syntax then
1081
1082         --  Acquire target parameters from system.ads (package System source)
1083
1084         Targparm_Acquire : declare
1085            use Sinput;
1086
1087            S : Source_File_Index;
1088            N : File_Name_Type;
1089
1090         begin
1091            Name_Buffer (1 .. 10) := "system.ads";
1092            Name_Len := 10;
1093            N := Name_Find;
1094            S := Load_Source_File (N);
1095
1096            --  Failed to read system.ads, fatal error
1097
1098            if S = No_Source_File then
1099               Write_Line
1100                 ("fatal error, run-time library not installed correctly");
1101               Write_Line ("cannot locate file system.ads");
1102               raise Unrecoverable_Error;
1103
1104            elsif S = No_Access_To_Source_File then
1105               Write_Line
1106                 ("fatal error, run-time library not installed correctly");
1107               Write_Line ("no read access for file system.ads");
1108               raise Unrecoverable_Error;
1109
1110            --  Read system.ads successfully, remember its source index
1111
1112            else
1113               System_Source_File_Index := S;
1114            end if;
1115
1116            --  Call to get target parameters. Note that the actual interface
1117            --  routines are in Tbuild. They can't be in this procedure because
1118            --  of accessibility issues.
1119
1120            Targparm.Get_Target_Parameters
1121              (System_Text  => Source_Text  (S),
1122               Source_First => Source_First (S),
1123               Source_Last  => Source_Last  (S),
1124               Make_Id      => Tbuild.Make_Id'Access,
1125               Make_SC      => Tbuild.Make_SC'Access,
1126               Set_NOD      => Tbuild.Set_NOD'Access,
1127               Set_NSA      => Tbuild.Set_NSA'Access,
1128               Set_NUA      => Tbuild.Set_NUA'Access,
1129               Set_NUP      => Tbuild.Set_NUP'Access);
1130
1131            --  Acquire configuration pragma information from Targparm
1132
1133            Restrict.Restrictions := Targparm.Restrictions_On_Target;
1134         end Targparm_Acquire;
1135      end if;
1136
1137      --  Perform various adjustments and settings of global switches
1138
1139      Adjust_Global_Switches;
1140
1141      --  Output copyright notice if full list mode unless we have a list
1142      --  file, in which case we defer this so that it is output in the file.
1143
1144      if (Verbose_Mode or else (Full_List and then Full_List_File_Name = null))
1145
1146        --  Debug flag gnatd7 suppresses this copyright notice
1147
1148        and then not Debug_Flag_7
1149      then
1150         Write_Eol;
1151         Write_Str ("GNAT ");
1152         Write_Str (Gnat_Version_String);
1153         Write_Eol;
1154         Write_Str ("Copyright 1992-" & Current_Year
1155                    & ", Free Software Foundation, Inc.");
1156         Write_Eol;
1157      end if;
1158
1159      --  Check we do not have more than one source file, this happens only in
1160      --  the case where the driver is called directly, it cannot happen when
1161      --  gnat1 is invoked from gcc in the normal case.
1162
1163      if Osint.Number_Of_Files /= 1 then
1164
1165         --  In GNATprove mode, gcc is not called, so we may end up with
1166         --  switches wrongly interpreted as source file names when they are
1167         --  written by mistake without a starting hyphen. Issue a specific
1168         --  error message but do not print the internal 'usage' message.
1169
1170         if GNATprove_Mode then
1171            Write_Str
1172              ("one of the following is not a valid switch or source file "
1173               & "name: ");
1174            Osint.Dump_Command_Line_Source_File_Names;
1175         else
1176            Usage;
1177            Write_Eol;
1178         end if;
1179
1180         Osint.Fail ("you must provide one source file");
1181
1182      elsif Usage_Requested then
1183         Usage;
1184      end if;
1185
1186      --  Generate target dependent output file if requested
1187
1188      if Target_Dependent_Info_Write_Name /= null then
1189         Set_Targ.Write_Target_Dependent_Values;
1190      end if;
1191
1192      --  Call the front end
1193
1194      Original_Operating_Mode := Operating_Mode;
1195      Frontend;
1196
1197      --  Exit with errors if the main source could not be parsed
1198
1199      if Sinput.Main_Source_File <= No_Source_File then
1200         Errout.Finalize (Last_Call => True);
1201         Errout.Output_Messages;
1202         Exit_Program (E_Errors);
1203      end if;
1204
1205      Main_Unit_Node := Cunit (Main_Unit);
1206      Main_Unit_Kind := Nkind (Unit (Main_Unit_Node));
1207
1208      Check_Bad_Body (Main_Unit_Node, Main_Unit_Kind);
1209
1210      --  In CodePeer mode we always delete old SCIL files before regenerating
1211      --  new ones, in case of e.g. errors, and also to remove obsolete scilx
1212      --  files generated by CodePeer itself.
1213
1214      if CodePeer_Mode then
1215         Comperr.Delete_SCIL_Files;
1216      end if;
1217
1218      --  Ditto for old C files before regenerating new ones
1219
1220      if Generate_C_Code then
1221         Delete_C_File;
1222         Delete_H_File;
1223      end if;
1224
1225      --  Exit if compilation errors detected
1226
1227      Errout.Finalize (Last_Call => False);
1228
1229      if Compilation_Errors then
1230         Treepr.Tree_Dump;
1231         Post_Compilation_Validation_Checks;
1232         Errout.Finalize (Last_Call => True);
1233         Errout.Output_Messages;
1234         Namet.Finalize;
1235
1236         --  Generate ALI file if specially requested
1237
1238         if Opt.Force_ALI_Tree_File then
1239            Write_ALI (Object => False);
1240            Tree_Gen;
1241         end if;
1242
1243         Exit_Program (E_Errors);
1244      end if;
1245
1246      --  Set Generate_Code on main unit and its spec. We do this even if are
1247      --  not generating code, since Lib-Writ uses this to determine which
1248      --  units get written in the ali file.
1249
1250      Set_Generate_Code (Main_Unit);
1251
1252      --  If we have a corresponding spec, and it comes from source or it is
1253      --  not a generated spec for a child subprogram body, then we need object
1254      --  code for the spec unit as well.
1255
1256      if Nkind (Unit (Main_Unit_Node)) in N_Unit_Body
1257        and then not Acts_As_Spec (Main_Unit_Node)
1258      then
1259         if Nkind (Unit (Main_Unit_Node)) = N_Subprogram_Body
1260           and then not Comes_From_Source (Library_Unit (Main_Unit_Node))
1261         then
1262            null;
1263         else
1264            Set_Generate_Code
1265              (Get_Cunit_Unit_Number (Library_Unit (Main_Unit_Node)));
1266         end if;
1267      end if;
1268
1269      --  Case of no code required to be generated, exit indicating no error
1270
1271      if Original_Operating_Mode = Check_Syntax then
1272         Treepr.Tree_Dump;
1273         Errout.Finalize (Last_Call => True);
1274         Errout.Output_Messages;
1275         Tree_Gen;
1276         Namet.Finalize;
1277         Check_Rep_Info;
1278
1279         --  Use a goto instead of calling Exit_Program so that finalization
1280         --  occurs normally.
1281
1282         goto End_Of_Program;
1283
1284      elsif Original_Operating_Mode = Check_Semantics then
1285         Back_End_Mode := Declarations_Only;
1286
1287      --  All remaining cases are cases in which the user requested that code
1288      --  be generated (i.e. no -gnatc or -gnats switch was used). Check if we
1289      --  can in fact satisfy this request.
1290
1291      --  Cannot generate code if someone has turned off code generation for
1292      --  any reason at all. We will try to figure out a reason below.
1293
1294      elsif Operating_Mode /= Generate_Code then
1295         Back_End_Mode := Skip;
1296
1297      --  We can generate code for a subprogram body unless there were missing
1298      --  subunits. Note that we always generate code for all generic units (a
1299      --  change from some previous versions of GNAT).
1300
1301      elsif Main_Unit_Kind = N_Subprogram_Body
1302        and then not Subunits_Missing
1303      then
1304         Back_End_Mode := Generate_Object;
1305
1306      --  We can generate code for a package body unless there are subunits
1307      --  missing (note that we always generate code for generic units, which
1308      --  is a change from some earlier versions of GNAT).
1309
1310      elsif Main_Unit_Kind = N_Package_Body and then not Subunits_Missing then
1311         Back_End_Mode := Generate_Object;
1312
1313      --  We can generate code for a package declaration or a subprogram
1314      --  declaration only if it does not required a body.
1315
1316      elsif Nkind_In (Main_Unit_Kind, N_Package_Declaration,
1317                                      N_Subprogram_Declaration)
1318        and then
1319          (not Body_Required (Main_Unit_Node)
1320             or else Distribution_Stub_Mode = Generate_Caller_Stub_Body)
1321      then
1322         Back_End_Mode := Generate_Object;
1323
1324      --  We can generate code for a generic package declaration of a generic
1325      --  subprogram declaration only if does not require a body.
1326
1327      elsif Nkind_In (Main_Unit_Kind, N_Generic_Package_Declaration,
1328                                      N_Generic_Subprogram_Declaration)
1329        and then not Body_Required (Main_Unit_Node)
1330      then
1331         Back_End_Mode := Generate_Object;
1332
1333      --  Compilation units that are renamings do not require bodies, so we can
1334      --  generate code for them.
1335
1336      elsif Nkind_In (Main_Unit_Kind, N_Package_Renaming_Declaration,
1337                                      N_Subprogram_Renaming_Declaration)
1338      then
1339         Back_End_Mode := Generate_Object;
1340
1341      --  Compilation units that are generic renamings do not require bodies
1342      --  so we can generate code for them.
1343
1344      elsif Main_Unit_Kind in N_Generic_Renaming_Declaration then
1345         Back_End_Mode := Generate_Object;
1346
1347      --  It is not an error to analyze in CodePeer mode a spec which requires
1348      --  a body, in order to generate SCIL for this spec.
1349      --  Ditto for Generate_C_Code mode and generate a C header for a spec.
1350
1351      elsif CodePeer_Mode or Generate_C_Code then
1352         Back_End_Mode := Generate_Object;
1353
1354      --  It is not an error to analyze in GNATprove mode a spec which requires
1355      --  a body, when the body is not available. During frame condition
1356      --  generation, the corresponding ALI file is generated. During
1357      --  analysis, the spec is analyzed.
1358
1359      elsif GNATprove_Mode then
1360         Back_End_Mode := Declarations_Only;
1361
1362      --  In all other cases (specs which have bodies, generics, and bodies
1363      --  where subunits are missing), we cannot generate code and we generate
1364      --  a warning message. Note that generic instantiations are gone at this
1365      --  stage since they have been replaced by their instances.
1366
1367      else
1368         Back_End_Mode := Skip;
1369      end if;
1370
1371      --  At this stage Back_End_Mode is set to indicate if the backend should
1372      --  be called to generate code. If it is Skip, then code generation has
1373      --  been turned off, even though code was requested by the original
1374      --  command. This is not an error from the user point of view, but it is
1375      --  an error from the point of view of the gcc driver, so we must exit
1376      --  with an error status.
1377
1378      --  We generate an informative message (from the gcc point of view, it
1379      --  is an error message, but from the users point of view this is not an
1380      --  error, just a consequence of compiling something that cannot
1381      --  generate code).
1382
1383      if Back_End_Mode = Skip then
1384
1385         --  An ignored Ghost unit is rewritten into a null statement because
1386         --  it must not produce an ALI or object file. Do not emit any errors
1387         --  related to code generation because the unit does not exist.
1388
1389         if Is_Ignored_Ghost_Unit (Main_Unit_Node) then
1390
1391            --  Exit the gnat driver with success, otherwise external builders
1392            --  such as gnatmake and gprbuild will treat the compilation of an
1393            --  ignored Ghost unit as a failure. Note that this will produce
1394            --  an empty object file for the unit.
1395
1396            Ecode := E_Success;
1397
1398         --  Otherwise the unit is missing a crucial piece that prevents code
1399         --  generation.
1400
1401         else
1402            Ecode := E_No_Code;
1403
1404            Set_Standard_Error;
1405            Write_Str ("cannot generate code for file ");
1406            Write_Name (Unit_File_Name (Main_Unit));
1407
1408            if Subunits_Missing then
1409               Write_Str (" (missing subunits)");
1410               Write_Eol;
1411
1412               --  Force generation of ALI file, for backward compatibility
1413
1414               Opt.Force_ALI_Tree_File := True;
1415
1416            elsif Main_Unit_Kind = N_Subunit then
1417               Write_Str (" (subunit)");
1418               Write_Eol;
1419
1420               --  Do not generate an ALI file in this case, because it would
1421               --  become obsolete when the parent is compiled, and thus
1422               --  confuse tools such as gnatfind.
1423
1424            elsif Main_Unit_Kind = N_Subprogram_Declaration then
1425               Write_Str (" (subprogram spec)");
1426               Write_Eol;
1427
1428            --  Generic package body in GNAT implementation mode
1429
1430            elsif Main_Unit_Kind = N_Package_Body and then GNAT_Mode then
1431               Write_Str (" (predefined generic)");
1432               Write_Eol;
1433
1434               --  Force generation of ALI file, for backward compatibility
1435
1436               Opt.Force_ALI_Tree_File := True;
1437
1438            --  Only other case is a package spec
1439
1440            else
1441               Write_Str (" (package spec)");
1442               Write_Eol;
1443            end if;
1444         end if;
1445
1446         Set_Standard_Output;
1447
1448         Post_Compilation_Validation_Checks;
1449         Errout.Finalize (Last_Call => True);
1450         Errout.Output_Messages;
1451         Treepr.Tree_Dump;
1452         Tree_Gen;
1453
1454         --  Generate ALI file if specially requested, or for missing subunits,
1455         --  subunits or predefined generic. For ignored ghost code, the object
1456         --  file IS generated, so Object should be True.
1457
1458         if Opt.Force_ALI_Tree_File then
1459            Write_ALI (Object => Is_Ignored_Ghost_Unit (Main_Unit_Node));
1460         end if;
1461
1462         Namet.Finalize;
1463         Check_Rep_Info;
1464
1465         --  Exit the driver with an appropriate status indicator. This will
1466         --  generate an empty object file for ignored Ghost units, otherwise
1467         --  no object file will be generated.
1468
1469         Exit_Program (Ecode);
1470      end if;
1471
1472      --  In -gnatc mode we only do annotation if -gnatt or -gnatR is also set,
1473      --  or if -gnatwz is enabled (default setting) and there is an unchecked
1474      --  conversion that involves a type whose size is not statically known,
1475      --  as indicated by Back_Annotate_Rep_Info being set to True.
1476
1477      --  We don't call for annotations on a subunit, because to process those
1478      --  the back end requires that the parent(s) be properly compiled.
1479
1480      --  Annotation is suppressed for targets where front-end layout is
1481      --  enabled, because the front end determines representations.
1482
1483      --  The back end is not invoked in ASIS mode with GNSA because all type
1484      --  representation information will be provided by the GNSA back end, not
1485      --  gigi.
1486
1487      --  A special back end is always called in CodePeer and GNATprove modes,
1488      --  unless this is a subunit.
1489
1490      if Back_End_Mode = Declarations_Only
1491        and then
1492          (not (Back_Annotate_Rep_Info or Generate_SCIL or GNATprove_Mode)
1493            or else Main_Unit_Kind = N_Subunit
1494            or else ASIS_GNSA_Mode)
1495      then
1496         Post_Compilation_Validation_Checks;
1497         Errout.Finalize (Last_Call => True);
1498         Errout.Output_Messages;
1499         Write_ALI (Object => False);
1500         Tree_Dump;
1501         Tree_Gen;
1502         Namet.Finalize;
1503
1504         if not (Generate_SCIL or GNATprove_Mode) then
1505            Check_Rep_Info;
1506         end if;
1507
1508         return;
1509      end if;
1510
1511      --  Ensure that we properly register a dependency on system.ads, since
1512      --  even if we do not semantically depend on this, Targparm has read
1513      --  system parameters from the system.ads file.
1514
1515      Lib.Writ.Ensure_System_Dependency;
1516
1517      --  Add dependencies, if any, on preprocessing data file and on
1518      --  preprocessing definition file(s).
1519
1520      Prepcomp.Add_Dependencies;
1521
1522      if GNATprove_Mode then
1523
1524         --  Perform the new SPARK checking rules for pointer aliasing. This is
1525         --  only activated in GNATprove mode and on SPARK code.
1526
1527         if Debug_Flag_FF then
1528            Check_Safe_Pointers (Main_Unit_Node);
1529         end if;
1530
1531         --  In GNATprove mode we're writing the ALI much earlier than usual
1532         --  as flow analysis needs the file present in order to append its
1533         --  own globals to it.
1534
1535         --  Note: In GNATprove mode, an "object" file is always generated as
1536         --  the result of calling gnat1 or gnat2why, although this is not the
1537         --  same as the object file produced for compilation.
1538
1539         Write_ALI (Object => True);
1540      end if;
1541
1542      --  Some back ends (for instance Gigi) are known to rely on SCOs for code
1543      --  generation. Make sure they are available.
1544
1545      if Generate_SCO then
1546         Par_SCO.SCO_Record_Filtered;
1547      end if;
1548
1549      --  Back end needs to explicitly unlock tables it needs to touch
1550
1551      Atree.Lock;
1552      Elists.Lock;
1553      Fname.UF.Lock;
1554      Ghost.Lock;
1555      Inline.Lock;
1556      Lib.Lock;
1557      Namet.Lock;
1558      Nlists.Lock;
1559      Sem.Lock;
1560      Sinput.Lock;
1561      Stringt.Lock;
1562
1563      --  Here we call the back end to generate the output code
1564
1565      Generating_Code := True;
1566      Back_End.Call_Back_End (Back_End_Mode);
1567
1568      --  Once the backend is complete, we unlock the names table. This call
1569      --  allows a few extra entries, needed for example for the file name
1570      --  for the library file output.
1571
1572      Namet.Unlock;
1573
1574      --  Generate the call-graph output of dispatching calls
1575
1576      Exp_CG.Generate_CG_Output;
1577
1578      --  Perform post compilation validation checks
1579
1580      Post_Compilation_Validation_Checks;
1581
1582      --  Now we complete output of errors, rep info and the tree info. These
1583      --  are delayed till now, since it is perfectly possible for gigi to
1584      --  generate errors, modify the tree (in particular by setting flags
1585      --  indicating that elaboration is required, and also to back annotate
1586      --  representation information for List_Rep_Info).
1587
1588      Errout.Finalize (Last_Call => True);
1589      Errout.Output_Messages;
1590      Repinfo.List_Rep_Info (Ttypes.Bytes_Big_Endian);
1591      Inline.List_Inlining_Info;
1592
1593      --  Only write the library if the backend did not generate any error
1594      --  messages. Otherwise signal errors to the driver program so that
1595      --  there will be no attempt to generate an object file.
1596
1597      if Compilation_Errors then
1598         Treepr.Tree_Dump;
1599         Exit_Program (E_Errors);
1600      end if;
1601
1602      if not GNATprove_Mode then
1603         Write_ALI (Object => (Back_End_Mode = Generate_Object));
1604      end if;
1605
1606      if not Compilation_Errors then
1607
1608         --  In case of ada backends, we need to make sure that the generated
1609         --  object file has a timestamp greater than the ALI file. We do this
1610         --  to make gnatmake happy when checking the ALI and obj timestamps,
1611         --  where it expects the object file being written after the ali file.
1612
1613         --  Gnatmake's assumption is true for gcc platforms where the gcc
1614         --  wrapper needs to call the assembler after calling gnat1, but is
1615         --  not true for ada backends, where the object files are created
1616         --  directly by gnat1 (so are created before the ali file).
1617
1618         Back_End.Gen_Or_Update_Object_File;
1619      end if;
1620
1621      --  Generate ASIS tree after writing the ALI file, since in ASIS mode,
1622      --  Write_ALI may in fact result in further tree decoration from the
1623      --  original tree file. Note that we dump the tree just before generating
1624      --  it, so that the dump will exactly reflect what is written out.
1625
1626      Treepr.Tree_Dump;
1627      Tree_Gen;
1628
1629      --  Finalize name table and we are all done
1630
1631      Namet.Finalize;
1632
1633   exception
1634      --  Handle fatal internal compiler errors
1635
1636      when Rtsfind.RE_Not_Available =>
1637         Comperr.Compiler_Abort ("RE_Not_Available");
1638
1639      when System.Assertions.Assert_Failure =>
1640         Comperr.Compiler_Abort ("Assert_Failure");
1641
1642      when Constraint_Error =>
1643         Comperr.Compiler_Abort ("Constraint_Error");
1644
1645      when Program_Error =>
1646         Comperr.Compiler_Abort ("Program_Error");
1647
1648      --  Assume this is a bug. If it is real, the message will in any case
1649      --  say Storage_Error, giving a strong hint.
1650
1651      when Storage_Error =>
1652         Comperr.Compiler_Abort ("Storage_Error");
1653
1654      when Unrecoverable_Error =>
1655         raise;
1656
1657      when others =>
1658         Comperr.Compiler_Abort ("exception");
1659   end;
1660
1661   <<End_Of_Program>>
1662   null;
1663
1664--  The outer exception handler handles an unrecoverable error
1665
1666exception
1667   when Unrecoverable_Error =>
1668      Errout.Finalize (Last_Call => True);
1669      Errout.Output_Messages;
1670
1671      Set_Standard_Error;
1672      Write_Str ("compilation abandoned");
1673      Write_Eol;
1674
1675      Set_Standard_Output;
1676      Source_Dump;
1677      Tree_Dump;
1678      Exit_Program (E_Errors);
1679
1680end Gnat1drv;
1681