OSDN Git Service

2010-08-05 Thomas Quinot <quinot@adacore.com>
[pf3gnuchains/gcc-fork.git] / gcc / ada / gnat1drv.adb
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-2010, 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
26 with Atree;    use Atree;
27 with Back_End; use Back_End;
28 with Comperr;
29 with Csets;    use Csets;
30 with Debug;    use Debug;
31 with Elists;
32 with Errout;   use Errout;
33 with Exp_CG;
34 with Fmap;
35 with Fname;    use Fname;
36 with Fname.UF; use Fname.UF;
37 with Frontend;
38 with Gnatvsn;  use Gnatvsn;
39 with Hostparm;
40 with Inline;
41 with Lib;      use Lib;
42 with Lib.Writ; use Lib.Writ;
43 with Lib.Xref;
44 with Namet;    use Namet;
45 with Nlists;
46 with Opt;      use Opt;
47 with Osint;    use Osint;
48 with Output;   use Output;
49 with Par_SCO;
50 with Prepcomp;
51 with Repinfo;  use Repinfo;
52 with Restrict;
53 with Rident;   use Rident;
54 with Rtsfind;
55 with SCOs;
56 with Sem;
57 with Sem_Ch8;
58 with Sem_Ch12;
59 with Sem_Ch13;
60 with Sem_Elim;
61 with Sem_Eval;
62 with Sem_Type;
63 with Sinfo;    use Sinfo;
64 with Sinput.L; use Sinput.L;
65 with Snames;
66 with Sprint;   use Sprint;
67 with Stringt;
68 with Stylesw;  use Stylesw;
69 with Targparm; use Targparm;
70 with Tree_Gen;
71 with Treepr;   use Treepr;
72 with Ttypes;
73 with Types;    use Types;
74 with Uintp;    use Uintp;
75 with Uname;    use Uname;
76 with Urealp;
77 with Usage;
78 with Validsw;  use Validsw;
79
80 with System.Assertions;
81
82 procedure Gnat1drv is
83    Main_Unit_Node : Node_Id;
84    --  Compilation unit node for main unit
85
86    Main_Kind : Node_Kind;
87    --  Kind of main compilation unit node
88
89    Back_End_Mode : Back_End.Back_End_Mode_Type;
90    --  Record back end mode
91
92    procedure Adjust_Global_Switches;
93    --  There are various interactions between front end switch settings,
94    --  including debug switch settings and target dependent parameters.
95    --  This procedure takes care of properly handling these interactions.
96    --  We do it after scanning out all the switches, so that we are not
97    --  depending on the order in which switches appear.
98
99    procedure Check_Bad_Body;
100    --  Called to check if the unit we are compiling has a bad body
101
102    procedure Check_Rep_Info;
103    --  Called when we are not generating code, to check if -gnatR was requested
104    --  and if so, explain that we will not be honoring the request.
105
106    procedure Check_Library_Items;
107    --  For debugging -- checks the behavior of Walk_Library_Items
108    pragma Warnings (Off, Check_Library_Items);
109    --  In case the call below is commented out
110
111    ----------------------------
112    -- Adjust_Global_Switches --
113    ----------------------------
114
115    procedure Adjust_Global_Switches is
116    begin
117       --  Debug flag -gnatd.I is a synonym for Generate_SCIL and requires code
118       --  generation.
119
120       if Debug_Flag_Dot_II
121         and then Operating_Mode = Generate_Code
122       then
123          Generate_SCIL := True;
124       end if;
125
126       --  Set ASIS mode if -gnatt and -gnatc are set
127
128       if Operating_Mode = Check_Semantics and then Tree_Output then
129          ASIS_Mode := True;
130
131          --  Turn off inlining in ASIS mode, since ASIS cannot handle the extra
132          --  information in the trees caused by inlining being active.
133
134          --  More specifically, the tree seems to be malformed from the ASIS
135          --  point of view if -gnatc and -gnatn appear together???
136
137          Inline_Active := False;
138
139          --  Turn off SCIL generation in ASIS mode, since SCIL requires front-
140          --  end expansion.
141
142          Generate_SCIL := False;
143       end if;
144
145       --  SCIL mode needs to disable front-end inlining since the generated
146       --  trees (in particular order and consistency between specs compiled
147       --  as part of a main unit or as part of a with-clause) are causing
148       --  troubles.
149
150       if Generate_SCIL then
151          Front_End_Inlining := False;
152       end if;
153
154       --  Tune settings for optimal SCIL generation in CodePeer_Mode
155
156       if CodePeer_Mode then
157
158          --  Turn off inlining, confuses CodePeer output and gains nothing
159
160          Front_End_Inlining := False;
161          Inline_Active      := False;
162
163          --  Turn off ASIS mode: incompatible with front-end expansion
164
165          ASIS_Mode := False;
166
167          --  Disable front-end optimizations, to keep the tree as close to the
168          --  source code as possible, and also to avoid inconsistencies between
169          --  trees when using different optimization switches.
170
171          Optimization_Level := 0;
172
173          --  Enable some restrictions systematically to simplify the generated
174          --  code (and ease analysis). Note that restriction checks are also
175          --  disabled in CodePeer_Mode, see Restrict.Check_Restriction
176
177          Restrict.Restrictions.Set (No_Task_Hierarchy) := True;
178          Restrict.Restrictions.Set (No_Abort_Statements) := True;
179          Restrict.Restrictions.Set (Max_Asynchronous_Select_Nesting) := True;
180          Restrict.Restrictions.Value (Max_Asynchronous_Select_Nesting) := 0;
181
182          --  Suppress overflow, division by zero and access checks since they
183          --  are handled implicitly by CodePeer.
184
185          --  Turn off dynamic elaboration checks: generates inconsistencies in
186          --  trees between specs compiled as part of a main unit or as part of
187          --  a with-clause.
188
189          --  Turn off alignment checks: these cannot be proved statically by
190          --  CodePeer and generate false positives.
191
192          --  Enable all other language checks
193
194          Suppress_Options :=
195            (Access_Check      => True,
196             Alignment_Check   => True,
197             Division_Check    => True,
198             Elaboration_Check => True,
199             Overflow_Check    => True,
200             others            => False);
201          Enable_Overflow_Checks := False;
202          Dynamic_Elaboration_Checks := False;
203
204          --  Kill debug of generated code, since it messes up sloc values
205
206          Debug_Generated_Code := False;
207
208          --  Turn cross-referencing on in case it was disabled (by e.g. -gnatD)
209          --  Do we really need to spend time generating xref in CodePeer
210          --  mode??? Consider setting Xref_Active to False.
211
212          Xref_Active := True;
213
214          --  Polling mode forced off, since it generates confusing junk
215
216          Polling_Required := False;
217
218          --  Set operating mode to Generate_Code to benefit from full
219          --  front-end expansion (e.g. generics).
220
221          Operating_Mode := Generate_Code;
222
223          --  We need SCIL generation of course
224
225          Generate_SCIL := True;
226
227          --  Enable assertions and debug pragmas, since they give CodePeer
228          --  valuable extra information.
229
230          Assertions_Enabled     := True;
231          Debug_Pragmas_Enabled  := True;
232
233          --  Suppress compiler warnings, since what we are interested in here
234          --  is what CodePeer can find out. Also disable all simple value
235          --  propagation. This is an optimization which is valuable for code
236          --  optimization, and also for generation of compiler warnings, but
237          --  these are being turned off anyway, and CodePeer understands
238          --  things more clearly if references are not optimized in this way.
239
240          Warning_Mode  := Suppress;
241          Debug_Flag_MM := True;
242
243          --  Set normal RM validity checking, and checking of IN OUT parameters
244          --  (this might give CodePeer more useful checks to analyze, to be
245          --  confirmed???). All other validity checking is turned off, since
246          --  this can generate very complex trees that only confuse CodePeer
247          --  and do not bring enough useful info.
248
249          Reset_Validity_Check_Options;
250          Validity_Check_Default       := True;
251          Validity_Check_In_Out_Params := True;
252          Validity_Check_In_Params     := True;
253
254          --  Turn off style check options since we are not interested in any
255          --  front-end warnings when we are getting CodePeer output.
256
257          Reset_Style_Check_Options;
258       end if;
259
260       --  Set Configurable_Run_Time mode if system.ads flag set
261
262       if Targparm.Configurable_Run_Time_On_Target or Debug_Flag_YY then
263          Configurable_Run_Time_Mode := True;
264       end if;
265
266       --  Set -gnatR3m mode if debug flag A set
267
268       if Debug_Flag_AA then
269          Back_Annotate_Rep_Info := True;
270          List_Representation_Info := 1;
271          List_Representation_Info_Mechanisms := True;
272       end if;
273
274       --  Force Target_Strict_Alignment true if debug flag -gnatd.a is set
275
276       if Debug_Flag_Dot_A then
277          Ttypes.Target_Strict_Alignment := True;
278       end if;
279
280       --  Disable static allocation of dispatch tables if -gnatd.t or if layout
281       --  is enabled. The front end's layout phase currently treats types that
282       --  have discriminant-dependent arrays as not being static even when a
283       --  discriminant constraint on the type is static, and this leads to
284       --  problems with subtypes of type Ada.Tags.Dispatch_Table_Wrapper. ???
285
286       if Debug_Flag_Dot_T or else Frontend_Layout_On_Target then
287          Static_Dispatch_Tables := False;
288       end if;
289
290       --  Flip endian mode if -gnatd8 set
291
292       if Debug_Flag_8 then
293          Ttypes.Bytes_Big_Endian := not Ttypes.Bytes_Big_Endian;
294       end if;
295
296       --  Deal with forcing OpenVMS switches True if debug flag M is set, but
297       --  record the setting of Targparm.Open_VMS_On_Target in True_VMS_Target
298       --  before doing this, so we know if we are in real OpenVMS or not!
299
300       Opt.True_VMS_Target := Targparm.OpenVMS_On_Target;
301
302       if Debug_Flag_M then
303          Targparm.OpenVMS_On_Target := True;
304          Hostparm.OpenVMS := True;
305       end if;
306
307       --  Activate front end layout if debug flag -gnatdF is set
308
309       if Debug_Flag_FF then
310          Targparm.Frontend_Layout_On_Target := True;
311       end if;
312
313       --  Set and check exception mechnism
314
315       if Targparm.ZCX_By_Default_On_Target then
316          if Targparm.GCC_ZCX_Support_On_Target then
317             Exception_Mechanism := Back_End_Exceptions;
318          else
319             Osint.Fail ("Zero Cost Exceptions not supported on this target");
320          end if;
321       end if;
322
323       --  Set proper status for overflow checks. We turn on overflow checks
324       --  if -gnatp was not specified, and either -gnato is set or the back
325       --  end takes care of overflow checks. Otherwise we suppress overflow
326       --  checks by default (since front end checks are expensive).
327
328       if not Opt.Suppress_Checks
329         and then (Opt.Enable_Overflow_Checks
330                     or else
331                       (Targparm.Backend_Divide_Checks_On_Target
332                         and
333                        Targparm.Backend_Overflow_Checks_On_Target))
334       then
335          Suppress_Options (Overflow_Check) := False;
336       else
337          Suppress_Options (Overflow_Check) := True;
338       end if;
339
340       --  Set switch indicating if we can use N_Expression_With_Actions
341
342       --  Debug flag -gnatd.X decisively sets usage on
343
344       if Debug_Flag_Dot_XX then
345          Use_Expression_With_Actions := True;
346
347       --  Debug flag -gnatd.Y decisively sets usage off
348
349       elsif Debug_Flag_Dot_YY then
350          Use_Expression_With_Actions := False;
351
352       --  If no debug flags, usage off for SCIL
353
354       elsif Generate_SCIL then
355          Use_Expression_With_Actions := False;
356
357       --  Otherwise this feature is implemented, so we allow its use
358
359       else
360          Use_Expression_With_Actions := True;
361       end if;
362
363       --  Set switch indicating if back end can handle limited types, and
364       --  guarantee that no incorrect copies are made (e.g. in the context
365       --  of a conditional expression).
366
367       --  Debug flag -gnatd.L decisively sets usage on
368
369       if Debug_Flag_Dot_LL then
370          Back_End_Handles_Limited_Types := True;
371
372       --  If no debug flag, usage off for AAMP, VM, SCIL cases
373
374       elsif AAMP_On_Target
375         or else VM_Target /= No_VM
376         or else Generate_SCIL
377       then
378          Back_End_Handles_Limited_Types := False;
379
380       --  Otherwise normal gcc back end, for now still turn flag off by
381       --  default, since there are unresolved problems in the front end.
382
383       else
384          Back_End_Handles_Limited_Types := False;
385       end if;
386    end Adjust_Global_Switches;
387
388    --------------------
389    -- Check_Bad_Body --
390    --------------------
391
392    procedure Check_Bad_Body is
393       Sname   : Unit_Name_Type;
394       Src_Ind : Source_File_Index;
395       Fname   : File_Name_Type;
396
397       procedure Bad_Body_Error (Msg : String);
398       --  Issue message for bad body found
399
400       --------------------
401       -- Bad_Body_Error --
402       --------------------
403
404       procedure Bad_Body_Error (Msg : String) is
405       begin
406          Error_Msg_N (Msg, Main_Unit_Node);
407          Error_Msg_File_1 := Fname;
408          Error_Msg_N ("remove incorrect body in file{!", Main_Unit_Node);
409       end Bad_Body_Error;
410
411       --  Start of processing for Check_Bad_Body
412
413    begin
414       --  Nothing to do if we are only checking syntax, because we don't know
415       --  enough to know if we require or forbid a body in this case.
416
417       if Operating_Mode = Check_Syntax then
418          return;
419       end if;
420
421       --  Check for body not allowed
422
423       if (Main_Kind = N_Package_Declaration
424            and then not Body_Required (Main_Unit_Node))
425         or else (Main_Kind = N_Generic_Package_Declaration
426                   and then not Body_Required (Main_Unit_Node))
427         or else Main_Kind = N_Package_Renaming_Declaration
428         or else Main_Kind = N_Subprogram_Renaming_Declaration
429         or else Nkind (Original_Node (Unit (Main_Unit_Node)))
430                          in N_Generic_Instantiation
431       then
432          Sname := Unit_Name (Main_Unit);
433
434          --  If we do not already have a body name, then get the body name
435          --  (but how can we have a body name here ???)
436
437          if not Is_Body_Name (Sname) then
438             Sname := Get_Body_Name (Sname);
439          end if;
440
441          Fname := Get_File_Name (Sname, Subunit => False);
442          Src_Ind := Load_Source_File (Fname);
443
444          --  Case where body is present and it is not a subunit. Exclude the
445          --  subunit case, because it has nothing to do with the package we are
446          --  compiling. It is illegal for a child unit and a subunit with the
447          --  same expanded name (RM 10.2(9)) to appear together in a partition,
448          --  but there is nothing to stop a compilation environment from having
449          --  both, and the test here simply allows that. If there is an attempt
450          --  to include both in a partition, this is diagnosed at bind time. In
451          --  Ada 83 mode this is not a warning case.
452
453          --  Note: if weird file names are being used, we can have a situation
454          --  where the file name that supposedly contains body in fact contains
455          --  a spec, or we can't tell what it contains. Skip the error message
456          --  in these cases.
457
458          --  Also ignore body that is nothing but pragma No_Body; (that's the
459          --  whole point of this pragma, to be used this way and to cause the
460          --  body file to be ignored in this context).
461
462          if Src_Ind /= No_Source_File
463            and then Get_Expected_Unit_Type (Fname) = Expect_Body
464            and then not Source_File_Is_Subunit (Src_Ind)
465            and then not Source_File_Is_No_Body (Src_Ind)
466          then
467             Errout.Finalize (Last_Call => False);
468
469             Error_Msg_Unit_1 := Sname;
470
471             --  Ada 83 case of a package body being ignored. This is not an
472             --  error as far as the Ada 83 RM is concerned, but it is almost
473             --  certainly not what is wanted so output a warning. Give this
474             --  message only if there were no errors, since otherwise it may
475             --  be incorrect (we may have misinterpreted a junk spec as not
476             --  needing a body when it really does).
477
478             if Main_Kind = N_Package_Declaration
479               and then Ada_Version = Ada_83
480               and then Operating_Mode = Generate_Code
481               and then Distribution_Stub_Mode /= Generate_Caller_Stub_Body
482               and then not Compilation_Errors
483             then
484                Error_Msg_N
485                  ("package $$ does not require a body?", Main_Unit_Node);
486                Error_Msg_File_1 := Fname;
487                Error_Msg_N ("body in file{? will be ignored", Main_Unit_Node);
488
489                --  Ada 95 cases of a body file present when no body is
490                --  permitted. This we consider to be an error.
491
492             else
493                --  For generic instantiations, we never allow a body
494
495                if Nkind (Original_Node (Unit (Main_Unit_Node)))
496                in N_Generic_Instantiation
497                then
498                   Bad_Body_Error
499                     ("generic instantiation for $$ does not allow a body");
500
501                   --  A library unit that is a renaming never allows a body
502
503                elsif Main_Kind in N_Renaming_Declaration then
504                   Bad_Body_Error
505                     ("renaming declaration for $$ does not allow a body!");
506
507                   --  Remaining cases are packages and generic packages. Here
508                   --  we only do the test if there are no previous errors,
509                   --  because if there are errors, they may lead us to
510                   --  incorrectly believe that a package does not allow a body
511                   --  when in fact it does.
512
513                elsif not Compilation_Errors then
514                   if Main_Kind = N_Package_Declaration then
515                      Bad_Body_Error
516                        ("package $$ does not allow a body!");
517
518                   elsif Main_Kind = N_Generic_Package_Declaration then
519                      Bad_Body_Error
520                        ("generic package $$ does not allow a body!");
521                   end if;
522                end if;
523
524             end if;
525          end if;
526       end if;
527    end Check_Bad_Body;
528
529    -------------------------
530    -- Check_Library_Items --
531    -------------------------
532
533    --  Walk_Library_Items has plenty of assertions, so all we need to do is
534    --  call it, just for these assertions, not actually doing anything else.
535
536    procedure Check_Library_Items is
537
538       procedure Action (Item : Node_Id);
539       --  Action passed to Walk_Library_Items to do nothing
540
541       ------------
542       -- Action --
543       ------------
544
545       procedure Action (Item : Node_Id) is
546       begin
547          null;
548       end Action;
549
550       procedure Walk is new Sem.Walk_Library_Items (Action);
551
552    --  Start of processing for Check_Library_Items
553
554    begin
555       Walk;
556    end Check_Library_Items;
557
558    --------------------
559    -- Check_Rep_Info --
560    --------------------
561
562    procedure Check_Rep_Info is
563    begin
564       if List_Representation_Info /= 0
565         or else List_Representation_Info_Mechanisms
566       then
567          Set_Standard_Error;
568          Write_Eol;
569          Write_Str
570            ("cannot generate representation information, no code generated");
571          Write_Eol;
572          Write_Eol;
573          Set_Standard_Output;
574       end if;
575    end Check_Rep_Info;
576
577 --  Start of processing for Gnat1drv
578
579 begin
580    --  This inner block is set up to catch assertion errors and constraint
581    --  errors. Since the code for handling these errors can cause another
582    --  exception to be raised (namely Unrecoverable_Error), we need two
583    --  nested blocks, so that the outer one handles unrecoverable error.
584
585    begin
586       --  Initialize all packages. For the most part, these initialization
587       --  calls can be made in any order. Exceptions are as follows:
588
589       --  Lib.Initialize need to be called before Scan_Compiler_Arguments,
590       --  because it initializes a table filled by Scan_Compiler_Arguments.
591
592       Osint.Initialize;
593       Fmap.Reset_Tables;
594       Lib.Initialize;
595       Lib.Xref.Initialize;
596       Scan_Compiler_Arguments;
597       Osint.Add_Default_Search_Dirs;
598
599       Nlists.Initialize;
600       Sinput.Initialize;
601       Sem.Initialize;
602       Exp_CG.Initialize;
603       Csets.Initialize;
604       Uintp.Initialize;
605       Urealp.Initialize;
606       Errout.Initialize;
607       Namet.Initialize;
608       SCOs.Initialize;
609       Snames.Initialize;
610       Stringt.Initialize;
611       Inline.Initialize;
612       Par_SCO.Initialize;
613       Sem_Ch8.Initialize;
614       Sem_Ch12.Initialize;
615       Sem_Ch13.Initialize;
616       Sem_Elim.Initialize;
617       Sem_Eval.Initialize;
618       Sem_Type.Init_Interp_Tables;
619
620       --  Acquire target parameters from system.ads (source of package System)
621
622       declare
623          use Sinput;
624
625          S : Source_File_Index;
626          N : File_Name_Type;
627
628       begin
629          Name_Buffer (1 .. 10) := "system.ads";
630          Name_Len := 10;
631          N := Name_Find;
632          S := Load_Source_File (N);
633
634          if S = No_Source_File then
635             Write_Line
636               ("fatal error, run-time library not installed correctly");
637             Write_Line ("cannot locate file system.ads");
638             raise Unrecoverable_Error;
639
640          --  Remember source index of system.ads (which was read successfully)
641
642          else
643             System_Source_File_Index := S;
644          end if;
645
646          Targparm.Get_Target_Parameters
647            (System_Text  => Source_Text  (S),
648             Source_First => Source_First (S),
649             Source_Last  => Source_Last  (S));
650
651          --  Acquire configuration pragma information from Targparm
652
653          Restrict.Restrictions := Targparm.Restrictions_On_Target;
654       end;
655
656       Adjust_Global_Switches;
657
658       --  Output copyright notice if full list mode unless we have a list
659       --  file, in which case we defer this so that it is output in the file
660
661       if (Verbose_Mode or else (Full_List and then Full_List_File_Name = null))
662         and then not Debug_Flag_7
663       then
664          Write_Eol;
665          Write_Str ("GNAT ");
666          Write_Str (Gnat_Version_String);
667          Write_Eol;
668          Write_Str ("Copyright 1992-" &
669                     Current_Year &
670                     ", Free Software Foundation, Inc.");
671          Write_Eol;
672       end if;
673
674       --  Check we do not have more than one source file, this happens only in
675       --  the case where the driver is called directly, it cannot happen when
676       --  gnat1 is invoked from gcc in the normal case.
677
678       if Osint.Number_Of_Files /= 1 then
679          Usage;
680          Write_Eol;
681          Osint.Fail ("you must provide one source file");
682
683       elsif Usage_Requested then
684          Usage;
685       end if;
686
687       Original_Operating_Mode := Operating_Mode;
688       Frontend;
689
690       --  Exit with errors if the main source could not be parsed
691
692       if Sinput.Main_Source_File = No_Source_File then
693          Errout.Finalize (Last_Call => True);
694          Errout.Output_Messages;
695          Exit_Program (E_Errors);
696       end if;
697
698       Main_Unit_Node := Cunit (Main_Unit);
699       Main_Kind := Nkind (Unit (Main_Unit_Node));
700       Check_Bad_Body;
701
702       --  Exit if compilation errors detected
703
704       Errout.Finalize (Last_Call => False);
705
706       if Compilation_Errors then
707          Treepr.Tree_Dump;
708          Sem_Ch13.Validate_Unchecked_Conversions;
709          Sem_Ch13.Validate_Address_Clauses;
710          Errout.Output_Messages;
711          Namet.Finalize;
712
713          --  Generate ALI file if specially requested
714
715          if Opt.Force_ALI_Tree_File then
716             Write_ALI (Object => False);
717             Tree_Gen;
718          end if;
719
720          Errout.Finalize (Last_Call => True);
721          Exit_Program (E_Errors);
722       end if;
723
724       --  Set Generate_Code on main unit and its spec. We do this even if are
725       --  not generating code, since Lib-Writ uses this to determine which
726       --  units get written in the ali file.
727
728       Set_Generate_Code (Main_Unit);
729
730       --  If we have a corresponding spec, and it comes from source
731       --  or it is not a generated spec for a child subprogram body,
732       --  then we need object code for the spec unit as well.
733
734       if Nkind (Unit (Main_Unit_Node)) in N_Unit_Body
735         and then not Acts_As_Spec (Main_Unit_Node)
736       then
737          if Nkind (Unit (Main_Unit_Node)) = N_Subprogram_Body
738            and then not Comes_From_Source (Library_Unit (Main_Unit_Node))
739          then
740             null;
741          else
742             Set_Generate_Code
743               (Get_Cunit_Unit_Number (Library_Unit (Main_Unit_Node)));
744          end if;
745       end if;
746
747       --  Case of no code required to be generated, exit indicating no error
748
749       if Original_Operating_Mode = Check_Syntax then
750          Treepr.Tree_Dump;
751          Errout.Finalize (Last_Call => True);
752          Errout.Output_Messages;
753          Tree_Gen;
754          Namet.Finalize;
755          Check_Rep_Info;
756
757          --  Use a goto instead of calling Exit_Program so that finalization
758          --  occurs normally.
759
760          goto End_Of_Program;
761
762       elsif Original_Operating_Mode = Check_Semantics then
763          Back_End_Mode := Declarations_Only;
764
765       --  All remaining cases are cases in which the user requested that code
766       --  be generated (i.e. no -gnatc or -gnats switch was used). Check if
767       --  we can in fact satisfy this request.
768
769       --  Cannot generate code if someone has turned off code generation for
770       --  any reason at all. We will try to figure out a reason below.
771
772       elsif Operating_Mode /= Generate_Code then
773          Back_End_Mode := Skip;
774
775       --  We can generate code for a subprogram body unless there were missing
776       --  subunits. Note that we always generate code for all generic units (a
777       --  change from some previous versions of GNAT).
778
779       elsif Main_Kind = N_Subprogram_Body and then not Subunits_Missing then
780          Back_End_Mode := Generate_Object;
781
782       --  We can generate code for a package body unless there are subunits
783       --  missing (note that we always generate code for generic units, which
784       --  is a change from some earlier versions of GNAT).
785
786       elsif Main_Kind = N_Package_Body and then not Subunits_Missing then
787          Back_End_Mode := Generate_Object;
788
789       --  We can generate code for a package declaration or a subprogram
790       --  declaration only if it does not required a body.
791
792       elsif (Main_Kind = N_Package_Declaration
793                or else
794              Main_Kind = N_Subprogram_Declaration)
795         and then
796           (not Body_Required (Main_Unit_Node)
797              or else
798            Distribution_Stub_Mode = Generate_Caller_Stub_Body)
799       then
800          Back_End_Mode := Generate_Object;
801
802       --  We can generate code for a generic package declaration of a generic
803       --  subprogram declaration only if does not require a body.
804
805       elsif (Main_Kind = N_Generic_Package_Declaration
806                or else
807              Main_Kind = N_Generic_Subprogram_Declaration)
808         and then not Body_Required (Main_Unit_Node)
809       then
810          Back_End_Mode := Generate_Object;
811
812       --  Compilation units that are renamings do not require bodies,
813       --  so we can generate code for them.
814
815       elsif Main_Kind = N_Package_Renaming_Declaration
816         or else Main_Kind = N_Subprogram_Renaming_Declaration
817       then
818          Back_End_Mode := Generate_Object;
819
820       --  Compilation units that are generic renamings do not require bodies
821       --  so we can generate code for them.
822
823       elsif Main_Kind in N_Generic_Renaming_Declaration then
824          Back_End_Mode := Generate_Object;
825
826       --  It's not an error to generate SCIL for e.g. a spec which has a body
827
828       elsif CodePeer_Mode then
829          Back_End_Mode := Generate_Object;
830
831       --  In all other cases (specs which have bodies, generics, and bodies
832       --  where subunits are missing), we cannot generate code and we generate
833       --  a warning message. Note that generic instantiations are gone at this
834       --  stage since they have been replaced by their instances.
835
836       else
837          Back_End_Mode := Skip;
838       end if;
839
840       --  At this stage Back_End_Mode is set to indicate if the backend should
841       --  be called to generate code. If it is Skip, then code generation has
842       --  been turned off, even though code was requested by the original
843       --  command. This is not an error from the user point of view, but it is
844       --  an error from the point of view of the gcc driver, so we must exit
845       --  with an error status.
846
847       --  We generate an informative message (from the gcc point of view, it
848       --  is an error message, but from the users point of view this is not an
849       --  error, just a consequence of compiling something that cannot
850       --  generate code).
851
852       if Back_End_Mode = Skip then
853          Set_Standard_Error;
854          Write_Str ("cannot generate code for ");
855          Write_Str ("file ");
856          Write_Name (Unit_File_Name (Main_Unit));
857
858          if Subunits_Missing then
859             Write_Str (" (missing subunits)");
860             Write_Eol;
861
862          elsif Main_Kind = N_Subunit then
863             Write_Str (" (subunit)");
864             Write_Eol;
865
866          elsif Main_Kind = N_Subprogram_Declaration then
867             Write_Str (" (subprogram spec)");
868             Write_Eol;
869
870          --  Generic package body in GNAT implementation mode
871
872          elsif Main_Kind = N_Package_Body and then GNAT_Mode then
873             Write_Str (" (predefined generic)");
874             Write_Eol;
875
876          --  Only other case is a package spec
877
878          else
879             Write_Str (" (package spec)");
880             Write_Eol;
881          end if;
882
883          Set_Standard_Output;
884
885          Sem_Ch13.Validate_Unchecked_Conversions;
886          Sem_Ch13.Validate_Address_Clauses;
887          Errout.Finalize (Last_Call => True);
888          Errout.Output_Messages;
889          Treepr.Tree_Dump;
890          Tree_Gen;
891          Write_ALI (Object => False);
892          Namet.Finalize;
893          Check_Rep_Info;
894
895          --  Exit program with error indication, to kill object file
896
897          Exit_Program (E_No_Code);
898       end if;
899
900       --  In -gnatc mode, we only do annotation if -gnatt or -gnatR is also set
901       --  as indicated by Back_Annotate_Rep_Info being set to True.
902
903       --  We don't call for annotations on a subunit, because to process those
904       --  the back-end requires that the parent(s) be properly compiled.
905
906       --  Annotation is suppressed for targets where front-end layout is
907       --  enabled, because the front end determines representations.
908
909       --  Annotation is also suppressed in the case of compiling for a VM,
910       --  since representations are largely symbolic there.
911
912       if Back_End_Mode = Declarations_Only
913         and then (not (Back_Annotate_Rep_Info or Generate_SCIL)
914                    or else Main_Kind = N_Subunit
915                    or else Targparm.Frontend_Layout_On_Target
916                    or else Targparm.VM_Target /= No_VM)
917       then
918          Sem_Ch13.Validate_Unchecked_Conversions;
919          Sem_Ch13.Validate_Address_Clauses;
920          Errout.Finalize (Last_Call => True);
921          Errout.Output_Messages;
922          Write_ALI (Object => False);
923          Tree_Dump;
924          Tree_Gen;
925          Namet.Finalize;
926          Check_Rep_Info;
927          return;
928       end if;
929
930       --  Ensure that we properly register a dependency on system.ads, since
931       --  even if we do not semantically depend on this, Targparm has read
932       --  system parameters from the system.ads file.
933
934       Lib.Writ.Ensure_System_Dependency;
935
936       --  Add dependencies, if any, on preprocessing data file and on
937       --  preprocessing definition file(s).
938
939       Prepcomp.Add_Dependencies;
940
941       --  Back end needs to explicitly unlock tables it needs to touch
942
943       Atree.Lock;
944       Elists.Lock;
945       Fname.UF.Lock;
946       Inline.Lock;
947       Lib.Lock;
948       Nlists.Lock;
949       Sem.Lock;
950       Sinput.Lock;
951       Namet.Lock;
952       Stringt.Lock;
953
954       --  ???Check_Library_Items under control of a debug flag, because it
955       --  currently does not work if the -gnatn switch (back end inlining) is
956       --  used.
957
958       if Debug_Flag_Dot_WW then
959          Check_Library_Items;
960       end if;
961
962       --  Here we call the back end to generate the output code
963
964       Generating_Code := True;
965       Back_End.Call_Back_End (Back_End_Mode);
966
967       --  Once the backend is complete, we unlock the names table. This call
968       --  allows a few extra entries, needed for example for the file name for
969       --  the library file output.
970
971       Namet.Unlock;
972
973       --  Generate the call-graph output of dispatching calls
974
975       Exp_CG.Generate_CG_Output;
976
977       --  Validate unchecked conversions (using the values for size and
978       --  alignment annotated by the backend where possible).
979
980       Sem_Ch13.Validate_Unchecked_Conversions;
981
982       --  Validate address clauses (again using alignment values annotated
983       --  by the backend where possible).
984
985       Sem_Ch13.Validate_Address_Clauses;
986
987       --  Now we complete output of errors, rep info and the tree info. These
988       --  are delayed till now, since it is perfectly possible for gigi to
989       --  generate errors, modify the tree (in particular by setting flags
990       --  indicating that elaboration is required, and also to back annotate
991       --  representation information for List_Rep_Info.
992
993       Errout.Finalize (Last_Call => True);
994       Errout.Output_Messages;
995       List_Rep_Info;
996
997       --  Only write the library if the backend did not generate any error
998       --  messages. Otherwise signal errors to the driver program so that
999       --  there will be no attempt to generate an object file.
1000
1001       if Compilation_Errors then
1002          Treepr.Tree_Dump;
1003          Exit_Program (E_Errors);
1004       end if;
1005
1006       Write_ALI (Object => (Back_End_Mode = Generate_Object));
1007
1008       --  Generate ASIS tree after writing the ALI file, since in ASIS mode,
1009       --  Write_ALI may in fact result in further tree decoration from the
1010       --  original tree file. Note that we dump the tree just before generating
1011       --  it, so that the dump will exactly reflect what is written out.
1012
1013       Treepr.Tree_Dump;
1014       Tree_Gen;
1015
1016       --  Finalize name table and we are all done
1017
1018       Namet.Finalize;
1019
1020    exception
1021       --  Handle fatal internal compiler errors
1022
1023       when Rtsfind.RE_Not_Available =>
1024          Comperr.Compiler_Abort ("RE_Not_Available");
1025
1026       when System.Assertions.Assert_Failure =>
1027          Comperr.Compiler_Abort ("Assert_Failure");
1028
1029       when Constraint_Error =>
1030          Comperr.Compiler_Abort ("Constraint_Error");
1031
1032       when Program_Error =>
1033          Comperr.Compiler_Abort ("Program_Error");
1034
1035       when Storage_Error =>
1036
1037          --  Assume this is a bug. If it is real, the message will in any case
1038          --  say Storage_Error, giving a strong hint!
1039
1040          Comperr.Compiler_Abort ("Storage_Error");
1041    end;
1042
1043    <<End_Of_Program>>
1044    null;
1045
1046    --  The outer exception handles an unrecoverable error
1047
1048 exception
1049    when Unrecoverable_Error =>
1050       Errout.Finalize (Last_Call => True);
1051       Errout.Output_Messages;
1052
1053       Set_Standard_Error;
1054       Write_Str ("compilation abandoned");
1055       Write_Eol;
1056
1057       Set_Standard_Output;
1058       Source_Dump;
1059       Tree_Dump;
1060       Exit_Program (E_Errors);
1061
1062 end Gnat1drv;