xref: /llvm-project/flang/lib/Frontend/CompilerInvocation.cpp (revision e7b6660243d1a4548f7aaac992b777ef0f0ba5b7)
1 //===- CompilerInvocation.cpp ---------------------------------------------===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 //
9 // Coding style: https://mlir.llvm.org/getting_started/DeveloperGuide/
10 //
11 //===----------------------------------------------------------------------===//
12 
13 #include "flang/Frontend/CompilerInvocation.h"
14 #include "flang/Common/Fortran-features.h"
15 #include "flang/Frontend/CodeGenOptions.h"
16 #include "flang/Frontend/PreprocessorOptions.h"
17 #include "flang/Frontend/TargetOptions.h"
18 #include "flang/Semantics/semantics.h"
19 #include "flang/Version.inc"
20 #include "clang/Basic/AllDiagnostics.h"
21 #include "clang/Basic/DiagnosticDriver.h"
22 #include "clang/Basic/DiagnosticOptions.h"
23 #include "clang/Driver/DriverDiagnostic.h"
24 #include "clang/Driver/OptionUtils.h"
25 #include "clang/Driver/Options.h"
26 #include "llvm/ADT/StringRef.h"
27 #include "llvm/ADT/StringSwitch.h"
28 #include "llvm/ADT/Triple.h"
29 #include "llvm/Option/Arg.h"
30 #include "llvm/Option/ArgList.h"
31 #include "llvm/Option/OptTable.h"
32 #include "llvm/Support/FileSystem.h"
33 #include "llvm/Support/FileUtilities.h"
34 #include "llvm/Support/Host.h"
35 #include "llvm/Support/Path.h"
36 #include "llvm/Support/Process.h"
37 #include "llvm/Support/raw_ostream.h"
38 #include <memory>
39 
40 using namespace Fortran::frontend;
41 
42 //===----------------------------------------------------------------------===//
43 // Initialization.
44 //===----------------------------------------------------------------------===//
45 CompilerInvocationBase::CompilerInvocationBase()
46     : diagnosticOpts(new clang::DiagnosticOptions()),
47       preprocessorOpts(new PreprocessorOptions()) {}
48 
49 CompilerInvocationBase::CompilerInvocationBase(const CompilerInvocationBase &x)
50     : diagnosticOpts(new clang::DiagnosticOptions(x.getDiagnosticOpts())),
51       preprocessorOpts(new PreprocessorOptions(x.getPreprocessorOpts())) {}
52 
53 CompilerInvocationBase::~CompilerInvocationBase() = default;
54 
55 //===----------------------------------------------------------------------===//
56 // Deserialization (from args)
57 //===----------------------------------------------------------------------===//
58 static bool parseShowColorsArgs(const llvm::opt::ArgList &args,
59                                 bool defaultColor = true) {
60   // Color diagnostics default to auto ("on" if terminal supports) in the
61   // compiler driver `flang-new` but default to off in the frontend driver
62   // `flang-new -fc1`, needing an explicit OPT_fdiagnostics_color.
63   // Support both clang's -f[no-]color-diagnostics and gcc's
64   // -f[no-]diagnostics-colors[=never|always|auto].
65   enum {
66     Colors_On,
67     Colors_Off,
68     Colors_Auto
69   } showColors = defaultColor ? Colors_Auto : Colors_Off;
70 
71   for (auto *a : args) {
72     const llvm::opt::Option &opt = a->getOption();
73     if (opt.matches(clang::driver::options::OPT_fcolor_diagnostics)) {
74       showColors = Colors_On;
75     } else if (opt.matches(clang::driver::options::OPT_fno_color_diagnostics)) {
76       showColors = Colors_Off;
77     } else if (opt.matches(clang::driver::options::OPT_fdiagnostics_color_EQ)) {
78       llvm::StringRef value(a->getValue());
79       if (value == "always")
80         showColors = Colors_On;
81       else if (value == "never")
82         showColors = Colors_Off;
83       else if (value == "auto")
84         showColors = Colors_Auto;
85     }
86   }
87 
88   return showColors == Colors_On ||
89          (showColors == Colors_Auto &&
90           llvm::sys::Process::StandardErrHasColors());
91 }
92 
93 /// Extracts the optimisation level from \a args.
94 static unsigned getOptimizationLevel(llvm::opt::ArgList &args,
95                                      clang::DiagnosticsEngine &diags) {
96   unsigned defaultOpt = llvm::CodeGenOpt::None;
97 
98   if (llvm::opt::Arg *a =
99           args.getLastArg(clang::driver::options::OPT_O_Group)) {
100     if (a->getOption().matches(clang::driver::options::OPT_O0))
101       return llvm::CodeGenOpt::None;
102 
103     assert(a->getOption().matches(clang::driver::options::OPT_O));
104 
105     return getLastArgIntValue(args, clang::driver::options::OPT_O, defaultOpt,
106                               diags);
107   }
108 
109   return defaultOpt;
110 }
111 
112 bool Fortran::frontend::parseDiagnosticArgs(clang::DiagnosticOptions &opts,
113                                             llvm::opt::ArgList &args) {
114   opts.ShowColors = parseShowColorsArgs(args);
115 
116   return true;
117 }
118 
119 static void parseCodeGenArgs(Fortran::frontend::CodeGenOptions &opts,
120                              llvm::opt::ArgList &args,
121                              clang::DiagnosticsEngine &diags) {
122   opts.OptimizationLevel = getOptimizationLevel(args, diags);
123 
124   if (args.hasFlag(clang::driver::options::OPT_fdebug_pass_manager,
125                    clang::driver::options::OPT_fno_debug_pass_manager, false))
126     opts.DebugPassManager = 1;
127 
128   for (auto *a : args.filtered(clang::driver::options::OPT_fpass_plugin_EQ))
129     opts.LLVMPassPlugins.push_back(a->getValue());
130 
131   // -mrelocation-model option.
132   if (const llvm::opt::Arg *A =
133           args.getLastArg(clang::driver::options::OPT_mrelocation_model)) {
134     llvm::StringRef ModelName = A->getValue();
135     auto RM = llvm::StringSwitch<llvm::Optional<llvm::Reloc::Model>>(ModelName)
136                   .Case("static", llvm::Reloc::Static)
137                   .Case("pic", llvm::Reloc::PIC_)
138                   .Case("dynamic-no-pic", llvm::Reloc::DynamicNoPIC)
139                   .Case("ropi", llvm::Reloc::ROPI)
140                   .Case("rwpi", llvm::Reloc::RWPI)
141                   .Case("ropi-rwpi", llvm::Reloc::ROPI_RWPI)
142                   .Default(std::nullopt);
143     if (RM.has_value())
144       opts.setRelocationModel(*RM);
145     else
146       diags.Report(clang::diag::err_drv_invalid_value)
147           << A->getAsString(args) << ModelName;
148   }
149 
150   // -pic-level and -pic-is-pie option.
151   if (int PICLevel = getLastArgIntValue(
152           args, clang::driver::options::OPT_pic_level, 0, diags)) {
153     if (PICLevel > 2)
154       diags.Report(clang::diag::err_drv_invalid_value)
155           << args.getLastArg(clang::driver::options::OPT_pic_level)
156                  ->getAsString(args)
157           << PICLevel;
158 
159     opts.PICLevel = PICLevel;
160     if (args.hasArg(clang::driver::options::OPT_pic_is_pie))
161       opts.IsPIE = 1;
162   }
163 }
164 
165 /// Parses all target input arguments and populates the target
166 /// options accordingly.
167 ///
168 /// \param [in] opts The target options instance to update
169 /// \param [in] args The list of input arguments (from the compiler invocation)
170 static void parseTargetArgs(TargetOptions &opts, llvm::opt::ArgList &args) {
171   if (const llvm::opt::Arg *a =
172           args.getLastArg(clang::driver::options::OPT_triple))
173     opts.triple = a->getValue();
174 
175   if (const llvm::opt::Arg *a =
176           args.getLastArg(clang::driver::options::OPT_target_cpu))
177     opts.cpu = a->getValue();
178 
179   for (const llvm::opt::Arg *currentArg :
180        args.filtered(clang::driver::options::OPT_target_feature))
181     opts.featuresAsWritten.emplace_back(currentArg->getValue());
182 }
183 
184 // Tweak the frontend configuration based on the frontend action
185 static void setUpFrontendBasedOnAction(FrontendOptions &opts) {
186   if (opts.programAction == DebugDumpParsingLog)
187     opts.instrumentedParse = true;
188 
189   if (opts.programAction == DebugDumpProvenance ||
190       opts.programAction == Fortran::frontend::GetDefinition)
191     opts.needProvenanceRangeToCharBlockMappings = true;
192 }
193 
194 /// Parse the argument specified for the -fconvert=<value> option
195 static std::optional<const char *> parseConvertArg(const char *s) {
196   return llvm::StringSwitch<std::optional<const char *>>(s)
197       .Case("unknown", "UNKNOWN")
198       .Case("native", "NATIVE")
199       .Case("little-endian", "LITTLE_ENDIAN")
200       .Case("big-endian", "BIG_ENDIAN")
201       .Case("swap", "SWAP")
202       .Default(std::nullopt);
203 }
204 
205 static bool parseFrontendArgs(FrontendOptions &opts, llvm::opt::ArgList &args,
206                               clang::DiagnosticsEngine &diags) {
207   unsigned numErrorsBefore = diags.getNumErrors();
208 
209   // By default the frontend driver creates a ParseSyntaxOnly action.
210   opts.programAction = ParseSyntaxOnly;
211 
212   // Treat multiple action options as an invocation error. Note that `clang
213   // -cc1` does accept multiple action options, but will only consider the
214   // rightmost one.
215   if (args.hasMultipleArgs(clang::driver::options::OPT_Action_Group)) {
216     const unsigned diagID = diags.getCustomDiagID(
217         clang::DiagnosticsEngine::Error, "Only one action option is allowed");
218     diags.Report(diagID);
219     return false;
220   }
221 
222   // Identify the action (i.e. opts.ProgramAction)
223   if (const llvm::opt::Arg *a =
224           args.getLastArg(clang::driver::options::OPT_Action_Group)) {
225     switch (a->getOption().getID()) {
226     default: {
227       llvm_unreachable("Invalid option in group!");
228     }
229     case clang::driver::options::OPT_test_io:
230       opts.programAction = InputOutputTest;
231       break;
232     case clang::driver::options::OPT_E:
233       opts.programAction = PrintPreprocessedInput;
234       break;
235     case clang::driver::options::OPT_fsyntax_only:
236       opts.programAction = ParseSyntaxOnly;
237       break;
238     case clang::driver::options::OPT_emit_mlir:
239       opts.programAction = EmitMLIR;
240       break;
241     case clang::driver::options::OPT_emit_llvm:
242       opts.programAction = EmitLLVM;
243       break;
244     case clang::driver::options::OPT_emit_llvm_bc:
245       opts.programAction = EmitLLVMBitcode;
246       break;
247     case clang::driver::options::OPT_emit_obj:
248       opts.programAction = EmitObj;
249       break;
250     case clang::driver::options::OPT_S:
251       opts.programAction = EmitAssembly;
252       break;
253     case clang::driver::options::OPT_fdebug_unparse:
254       opts.programAction = DebugUnparse;
255       break;
256     case clang::driver::options::OPT_fdebug_unparse_no_sema:
257       opts.programAction = DebugUnparseNoSema;
258       break;
259     case clang::driver::options::OPT_fdebug_unparse_with_symbols:
260       opts.programAction = DebugUnparseWithSymbols;
261       break;
262     case clang::driver::options::OPT_fdebug_dump_symbols:
263       opts.programAction = DebugDumpSymbols;
264       break;
265     case clang::driver::options::OPT_fdebug_dump_parse_tree:
266       opts.programAction = DebugDumpParseTree;
267       break;
268     case clang::driver::options::OPT_fdebug_dump_pft:
269       opts.programAction = DebugDumpPFT;
270       break;
271     case clang::driver::options::OPT_fdebug_dump_all:
272       opts.programAction = DebugDumpAll;
273       break;
274     case clang::driver::options::OPT_fdebug_dump_parse_tree_no_sema:
275       opts.programAction = DebugDumpParseTreeNoSema;
276       break;
277     case clang::driver::options::OPT_fdebug_dump_provenance:
278       opts.programAction = DebugDumpProvenance;
279       break;
280     case clang::driver::options::OPT_fdebug_dump_parsing_log:
281       opts.programAction = DebugDumpParsingLog;
282       break;
283     case clang::driver::options::OPT_fdebug_measure_parse_tree:
284       opts.programAction = DebugMeasureParseTree;
285       break;
286     case clang::driver::options::OPT_fdebug_pre_fir_tree:
287       opts.programAction = DebugPreFIRTree;
288       break;
289     case clang::driver::options::OPT_fget_symbols_sources:
290       opts.programAction = GetSymbolsSources;
291       break;
292     case clang::driver::options::OPT_fget_definition:
293       opts.programAction = GetDefinition;
294       break;
295     case clang::driver::options::OPT_init_only:
296       opts.programAction = InitOnly;
297       break;
298 
299       // TODO:
300       // case clang::driver::options::OPT_emit_llvm:
301       // case clang::driver::options::OPT_emit_llvm_only:
302       // case clang::driver::options::OPT_emit_codegen_only:
303       // case clang::driver::options::OPT_emit_module:
304       // (...)
305     }
306 
307     // Parse the values provided with `-fget-definition` (there should be 3
308     // integers)
309     if (llvm::opt::OptSpecifier(a->getOption().getID()) ==
310         clang::driver::options::OPT_fget_definition) {
311       unsigned optVals[3] = {0, 0, 0};
312 
313       for (unsigned i = 0; i < 3; i++) {
314         llvm::StringRef val = a->getValue(i);
315 
316         if (val.getAsInteger(10, optVals[i])) {
317           // A non-integer was encountered - that's an error.
318           diags.Report(clang::diag::err_drv_invalid_value)
319               << a->getOption().getName() << val;
320           break;
321         }
322       }
323       opts.getDefVals.line = optVals[0];
324       opts.getDefVals.startColumn = optVals[1];
325       opts.getDefVals.endColumn = optVals[2];
326     }
327   }
328 
329   // Parsing -load <dsopath> option and storing shared object path
330   if (llvm::opt::Arg *a = args.getLastArg(clang::driver::options::OPT_load)) {
331     opts.plugins.push_back(a->getValue());
332   }
333 
334   // Parsing -plugin <name> option and storing plugin name and setting action
335   if (const llvm::opt::Arg *a =
336           args.getLastArg(clang::driver::options::OPT_plugin)) {
337     opts.programAction = PluginAction;
338     opts.actionName = a->getValue();
339   }
340 
341   opts.outputFile = args.getLastArgValue(clang::driver::options::OPT_o);
342   opts.showHelp = args.hasArg(clang::driver::options::OPT_help);
343   opts.showVersion = args.hasArg(clang::driver::options::OPT_version);
344 
345   // Get the input kind (from the value passed via `-x`)
346   InputKind dashX(Language::Unknown);
347   if (const llvm::opt::Arg *a =
348           args.getLastArg(clang::driver::options::OPT_x)) {
349     llvm::StringRef xValue = a->getValue();
350     // Principal languages.
351     dashX = llvm::StringSwitch<InputKind>(xValue)
352                 // Flang does not differentiate between pre-processed and not
353                 // pre-processed inputs.
354                 .Case("f95", Language::Fortran)
355                 .Case("f95-cpp-input", Language::Fortran)
356                 .Default(Language::Unknown);
357 
358     // Flang's intermediate representations.
359     if (dashX.isUnknown())
360       dashX = llvm::StringSwitch<InputKind>(xValue)
361                   .Case("ir", Language::LLVM_IR)
362                   .Case("fir", Language::MLIR)
363                   .Case("mlir", Language::MLIR)
364                   .Default(Language::Unknown);
365 
366     if (dashX.isUnknown())
367       diags.Report(clang::diag::err_drv_invalid_value)
368           << a->getAsString(args) << a->getValue();
369   }
370 
371   // Collect the input files and save them in our instance of FrontendOptions.
372   std::vector<std::string> inputs =
373       args.getAllArgValues(clang::driver::options::OPT_INPUT);
374   opts.inputs.clear();
375   if (inputs.empty())
376     // '-' is the default input if none is given.
377     inputs.push_back("-");
378   for (unsigned i = 0, e = inputs.size(); i != e; ++i) {
379     InputKind ik = dashX;
380     if (ik.isUnknown()) {
381       ik = FrontendOptions::getInputKindForExtension(
382           llvm::StringRef(inputs[i]).rsplit('.').second);
383       if (ik.isUnknown())
384         ik = Language::Unknown;
385       if (i == 0)
386         dashX = ik;
387     }
388 
389     opts.inputs.emplace_back(std::move(inputs[i]), ik);
390   }
391 
392   // Set fortranForm based on options -ffree-form and -ffixed-form.
393   if (const auto *arg =
394           args.getLastArg(clang::driver::options::OPT_ffixed_form,
395                           clang::driver::options::OPT_ffree_form)) {
396     opts.fortranForm =
397         arg->getOption().matches(clang::driver::options::OPT_ffixed_form)
398             ? FortranForm::FixedForm
399             : FortranForm::FreeForm;
400   }
401 
402   // Set fixedFormColumns based on -ffixed-line-length=<value>
403   if (const auto *arg =
404           args.getLastArg(clang::driver::options::OPT_ffixed_line_length_EQ)) {
405     llvm::StringRef argValue = llvm::StringRef(arg->getValue());
406     std::int64_t columns = -1;
407     if (argValue == "none") {
408       columns = 0;
409     } else if (argValue.getAsInteger(/*Radix=*/10, columns)) {
410       columns = -1;
411     }
412     if (columns < 0) {
413       diags.Report(clang::diag::err_drv_negative_columns)
414           << arg->getOption().getName() << arg->getValue();
415     } else if (columns == 0) {
416       opts.fixedFormColumns = 1000000;
417     } else if (columns < 7) {
418       diags.Report(clang::diag::err_drv_small_columns)
419           << arg->getOption().getName() << arg->getValue() << "7";
420     } else {
421       opts.fixedFormColumns = columns;
422     }
423   }
424 
425   // Set conversion based on -fconvert=<value>
426   if (const auto *arg =
427           args.getLastArg(clang::driver::options::OPT_fconvert_EQ)) {
428     const char *argValue = arg->getValue();
429     if (auto convert = parseConvertArg(argValue))
430       opts.envDefaults.push_back({"FORT_CONVERT", *convert});
431     else
432       diags.Report(clang::diag::err_drv_invalid_value)
433           << arg->getAsString(args) << argValue;
434   }
435 
436   // -f{no-}implicit-none
437   opts.features.Enable(
438       Fortran::common::LanguageFeature::ImplicitNoneTypeAlways,
439       args.hasFlag(clang::driver::options::OPT_fimplicit_none,
440                    clang::driver::options::OPT_fno_implicit_none, false));
441 
442   // -f{no-}backslash
443   opts.features.Enable(Fortran::common::LanguageFeature::BackslashEscapes,
444                        args.hasFlag(clang::driver::options::OPT_fbackslash,
445                                     clang::driver::options::OPT_fno_backslash,
446                                     false));
447 
448   // -f{no-}logical-abbreviations
449   opts.features.Enable(
450       Fortran::common::LanguageFeature::LogicalAbbreviations,
451       args.hasFlag(clang::driver::options::OPT_flogical_abbreviations,
452                    clang::driver::options::OPT_fno_logical_abbreviations,
453                    false));
454 
455   // -f{no-}xor-operator
456   opts.features.Enable(
457       Fortran::common::LanguageFeature::XOROperator,
458       args.hasFlag(clang::driver::options::OPT_fxor_operator,
459                    clang::driver::options::OPT_fno_xor_operator, false));
460 
461   // -fno-automatic
462   if (args.hasArg(clang::driver::options::OPT_fno_automatic)) {
463     opts.features.Enable(Fortran::common::LanguageFeature::DefaultSave);
464   }
465 
466   if (args.hasArg(
467           clang::driver::options::OPT_falternative_parameter_statement)) {
468     opts.features.Enable(Fortran::common::LanguageFeature::OldStyleParameter);
469   }
470   if (const llvm::opt::Arg *arg =
471           args.getLastArg(clang::driver::options::OPT_finput_charset_EQ)) {
472     llvm::StringRef argValue = arg->getValue();
473     if (argValue == "utf-8") {
474       opts.encoding = Fortran::parser::Encoding::UTF_8;
475     } else if (argValue == "latin-1") {
476       opts.encoding = Fortran::parser::Encoding::LATIN_1;
477     } else {
478       diags.Report(clang::diag::err_drv_invalid_value)
479           << arg->getAsString(args) << argValue;
480     }
481   }
482 
483   setUpFrontendBasedOnAction(opts);
484   opts.dashX = dashX;
485 
486   return diags.getNumErrors() == numErrorsBefore;
487 }
488 
489 // Generate the path to look for intrinsic modules
490 static std::string getIntrinsicDir() {
491   // TODO: Find a system independent API
492   llvm::SmallString<128> driverPath;
493   driverPath.assign(llvm::sys::fs::getMainExecutable(nullptr, nullptr));
494   llvm::sys::path::remove_filename(driverPath);
495   driverPath.append("/../include/flang/");
496   return std::string(driverPath);
497 }
498 
499 // Generate the path to look for OpenMP headers
500 static std::string getOpenMPHeadersDir() {
501   llvm::SmallString<128> includePath;
502   includePath.assign(llvm::sys::fs::getMainExecutable(nullptr, nullptr));
503   llvm::sys::path::remove_filename(includePath);
504   includePath.append("/../include/flang/OpenMP/");
505   return std::string(includePath);
506 }
507 
508 /// Parses all preprocessor input arguments and populates the preprocessor
509 /// options accordingly.
510 ///
511 /// \param [in] opts The preprocessor options instance
512 /// \param [out] args The list of input arguments
513 static void parsePreprocessorArgs(Fortran::frontend::PreprocessorOptions &opts,
514                                   llvm::opt::ArgList &args) {
515   // Add macros from the command line.
516   for (const auto *currentArg : args.filtered(clang::driver::options::OPT_D,
517                                               clang::driver::options::OPT_U)) {
518     if (currentArg->getOption().matches(clang::driver::options::OPT_D)) {
519       opts.addMacroDef(currentArg->getValue());
520     } else {
521       opts.addMacroUndef(currentArg->getValue());
522     }
523   }
524 
525   // Add the ordered list of -I's.
526   for (const auto *currentArg : args.filtered(clang::driver::options::OPT_I))
527     opts.searchDirectoriesFromDashI.emplace_back(currentArg->getValue());
528 
529   // Prepend the ordered list of -intrinsic-modules-path
530   // to the default location to search.
531   for (const auto *currentArg :
532        args.filtered(clang::driver::options::OPT_fintrinsic_modules_path))
533     opts.searchDirectoriesFromIntrModPath.emplace_back(currentArg->getValue());
534 
535   // -cpp/-nocpp
536   if (const auto *currentArg = args.getLastArg(
537           clang::driver::options::OPT_cpp, clang::driver::options::OPT_nocpp))
538     opts.macrosFlag =
539         (currentArg->getOption().matches(clang::driver::options::OPT_cpp))
540             ? PPMacrosFlag::Include
541             : PPMacrosFlag::Exclude;
542 
543   opts.noReformat = args.hasArg(clang::driver::options::OPT_fno_reformat);
544   opts.noLineDirectives = args.hasArg(clang::driver::options::OPT_P);
545 }
546 
547 /// Parses all semantic related arguments and populates the variables
548 /// options accordingly. Returns false if new errors are generated.
549 static bool parseSemaArgs(CompilerInvocation &res, llvm::opt::ArgList &args,
550                           clang::DiagnosticsEngine &diags) {
551   unsigned numErrorsBefore = diags.getNumErrors();
552 
553   // -J/module-dir option
554   auto moduleDirList =
555       args.getAllArgValues(clang::driver::options::OPT_module_dir);
556   // User can only specify -J/-module-dir once
557   // https://gcc.gnu.org/onlinedocs/gfortran/Directory-Options.html
558   if (moduleDirList.size() > 1) {
559     const unsigned diagID =
560         diags.getCustomDiagID(clang::DiagnosticsEngine::Error,
561                               "Only one '-module-dir/-J' option allowed");
562     diags.Report(diagID);
563   }
564   if (moduleDirList.size() == 1)
565     res.setModuleDir(moduleDirList[0]);
566 
567   // -fdebug-module-writer option
568   if (args.hasArg(clang::driver::options::OPT_fdebug_module_writer)) {
569     res.setDebugModuleDir(true);
570   }
571 
572   // -module-suffix
573   if (const auto *moduleSuffix =
574           args.getLastArg(clang::driver::options::OPT_module_suffix)) {
575     res.setModuleFileSuffix(moduleSuffix->getValue());
576   }
577 
578   // -f{no-}analyzed-objects-for-unparse
579   res.setUseAnalyzedObjectsForUnparse(args.hasFlag(
580       clang::driver::options::OPT_fanalyzed_objects_for_unparse,
581       clang::driver::options::OPT_fno_analyzed_objects_for_unparse, true));
582 
583   return diags.getNumErrors() == numErrorsBefore;
584 }
585 
586 /// Parses all diagnostics related arguments and populates the variables
587 /// options accordingly. Returns false if new errors are generated.
588 static bool parseDiagArgs(CompilerInvocation &res, llvm::opt::ArgList &args,
589                           clang::DiagnosticsEngine &diags) {
590   unsigned numErrorsBefore = diags.getNumErrors();
591 
592   // -Werror option
593   // TODO: Currently throws a Diagnostic for anything other than -W<error>,
594   // this has to change when other -W<opt>'s are supported.
595   if (args.hasArg(clang::driver::options::OPT_W_Joined)) {
596     if (args.getLastArgValue(clang::driver::options::OPT_W_Joined)
597             .equals("error")) {
598       res.setWarnAsErr(true);
599     } else {
600       const unsigned diagID =
601           diags.getCustomDiagID(clang::DiagnosticsEngine::Error,
602                                 "Only `-Werror` is supported currently.");
603       diags.Report(diagID);
604     }
605   }
606 
607   // Default to off for `flang-new -fc1`.
608   res.getFrontendOpts().showColors =
609       parseShowColorsArgs(args, /*defaultDiagColor=*/false);
610 
611   return diags.getNumErrors() == numErrorsBefore;
612 }
613 
614 /// Parses all Dialect related arguments and populates the variables
615 /// options accordingly. Returns false if new errors are generated.
616 static bool parseDialectArgs(CompilerInvocation &res, llvm::opt::ArgList &args,
617                              clang::DiagnosticsEngine &diags) {
618   unsigned numErrorsBefore = diags.getNumErrors();
619 
620   // -fdefault* family
621   if (args.hasArg(clang::driver::options::OPT_fdefault_real_8)) {
622     res.getDefaultKinds().set_defaultRealKind(8);
623     res.getDefaultKinds().set_doublePrecisionKind(16);
624   }
625   if (args.hasArg(clang::driver::options::OPT_fdefault_integer_8)) {
626     res.getDefaultKinds().set_defaultIntegerKind(8);
627     res.getDefaultKinds().set_subscriptIntegerKind(8);
628     res.getDefaultKinds().set_sizeIntegerKind(8);
629   }
630   if (args.hasArg(clang::driver::options::OPT_fdefault_double_8)) {
631     if (!args.hasArg(clang::driver::options::OPT_fdefault_real_8)) {
632       // -fdefault-double-8 has to be used with -fdefault-real-8
633       // to be compatible with gfortran
634       const unsigned diagID = diags.getCustomDiagID(
635           clang::DiagnosticsEngine::Error,
636           "Use of `-fdefault-double-8` requires `-fdefault-real-8`");
637       diags.Report(diagID);
638     }
639     // https://gcc.gnu.org/onlinedocs/gfortran/Fortran-Dialect-Options.html
640     res.getDefaultKinds().set_doublePrecisionKind(8);
641   }
642   if (args.hasArg(clang::driver::options::OPT_flarge_sizes))
643     res.getDefaultKinds().set_sizeIntegerKind(8);
644 
645   // -fopenmp and -fopenacc
646   if (args.hasArg(clang::driver::options::OPT_fopenacc)) {
647     res.getFrontendOpts().features.Enable(
648         Fortran::common::LanguageFeature::OpenACC);
649   }
650   if (args.hasArg(clang::driver::options::OPT_fopenmp)) {
651     res.getFrontendOpts().features.Enable(
652         Fortran::common::LanguageFeature::OpenMP);
653   }
654 
655   // -pedantic
656   if (args.hasArg(clang::driver::options::OPT_pedantic)) {
657     res.setEnableConformanceChecks();
658   }
659   // -std=f2018 (currently this implies -pedantic)
660   // TODO: Set proper options when more fortran standards
661   // are supported.
662   if (args.hasArg(clang::driver::options::OPT_std_EQ)) {
663     auto standard = args.getLastArgValue(clang::driver::options::OPT_std_EQ);
664     // We only allow f2018 as the given standard
665     if (standard.equals("f2018")) {
666       res.setEnableConformanceChecks();
667     } else {
668       const unsigned diagID =
669           diags.getCustomDiagID(clang::DiagnosticsEngine::Error,
670                                 "Only -std=f2018 is allowed currently.");
671       diags.Report(diagID);
672     }
673   }
674   return diags.getNumErrors() == numErrorsBefore;
675 }
676 
677 /// Parses all floating point related arguments and populates the
678 /// CompilerInvocation accordingly.
679 /// Returns false if new errors are generated.
680 ///
681 /// \param [out] invoc Stores the processed arguments
682 /// \param [in] args The compiler invocation arguments to parse
683 /// \param [out] diags DiagnosticsEngine to report erros with
684 static bool parseFloatingPointArgs(CompilerInvocation &invoc,
685                                    llvm::opt::ArgList &args,
686                                    clang::DiagnosticsEngine &diags) {
687   LangOptions &opts = invoc.getLangOpts();
688 
689   if (const llvm::opt::Arg *a =
690           args.getLastArg(clang::driver::options::OPT_ffp_contract)) {
691     const llvm::StringRef val = a->getValue();
692     enum LangOptions::FPModeKind fpContractMode;
693 
694     if (val == "off")
695       fpContractMode = LangOptions::FPM_Off;
696     else if (val == "fast")
697       fpContractMode = LangOptions::FPM_Fast;
698     else {
699       diags.Report(clang::diag::err_drv_unsupported_option_argument)
700           << a->getSpelling() << val;
701       return false;
702     }
703 
704     opts.setFPContractMode(fpContractMode);
705   }
706 
707   if (args.getLastArg(clang::driver::options::OPT_menable_no_infinities)) {
708     opts.NoHonorInfs = true;
709   }
710 
711   if (args.getLastArg(clang::driver::options::OPT_menable_no_nans)) {
712     opts.NoHonorNaNs = true;
713   }
714 
715   if (args.getLastArg(clang::driver::options::OPT_fapprox_func)) {
716     opts.ApproxFunc = true;
717   }
718 
719   if (args.getLastArg(clang::driver::options::OPT_fno_signed_zeros)) {
720     opts.NoSignedZeros = true;
721   }
722 
723   if (args.getLastArg(clang::driver::options::OPT_mreassociate)) {
724     opts.AssociativeMath = true;
725   }
726 
727   if (args.getLastArg(clang::driver::options::OPT_freciprocal_math)) {
728     opts.ReciprocalMath = true;
729   }
730 
731   if (args.getLastArg(clang::driver::options::OPT_ffast_math)) {
732     opts.NoHonorInfs = true;
733     opts.NoHonorNaNs = true;
734     opts.AssociativeMath = true;
735     opts.ReciprocalMath = true;
736     opts.ApproxFunc = true;
737     opts.NoSignedZeros = true;
738     opts.setFPContractMode(LangOptions::FPM_Fast);
739   }
740 
741   return true;
742 }
743 
744 bool CompilerInvocation::createFromArgs(
745     CompilerInvocation &res, llvm::ArrayRef<const char *> commandLineArgs,
746     clang::DiagnosticsEngine &diags) {
747 
748   bool success = true;
749 
750   // Set the default triple for this CompilerInvocation. This might be
751   // overridden by users with `-triple` (see the call to `ParseTargetArgs`
752   // below).
753   // NOTE: Like in Clang, it would be nice to use option marshalling
754   // for this so that the entire logic for setting-up the triple is in one
755   // place.
756   res.getTargetOpts().triple =
757       llvm::Triple::normalize(llvm::sys::getDefaultTargetTriple());
758 
759   // Parse the arguments
760   const llvm::opt::OptTable &opts = clang::driver::getDriverOptTable();
761   const unsigned includedFlagsBitmask = clang::driver::options::FC1Option;
762   unsigned missingArgIndex, missingArgCount;
763   llvm::opt::InputArgList args = opts.ParseArgs(
764       commandLineArgs, missingArgIndex, missingArgCount, includedFlagsBitmask);
765 
766   // Check for missing argument error.
767   if (missingArgCount) {
768     diags.Report(clang::diag::err_drv_missing_argument)
769         << args.getArgString(missingArgIndex) << missingArgCount;
770     success = false;
771   }
772 
773   // Issue errors on unknown arguments
774   for (const auto *a : args.filtered(clang::driver::options::OPT_UNKNOWN)) {
775     auto argString = a->getAsString(args);
776     std::string nearest;
777     if (opts.findNearest(argString, nearest, includedFlagsBitmask) > 1)
778       diags.Report(clang::diag::err_drv_unknown_argument) << argString;
779     else
780       diags.Report(clang::diag::err_drv_unknown_argument_with_suggestion)
781           << argString << nearest;
782     success = false;
783   }
784 
785   success &= parseFrontendArgs(res.getFrontendOpts(), args, diags);
786   parseTargetArgs(res.getTargetOpts(), args);
787   parsePreprocessorArgs(res.getPreprocessorOpts(), args);
788   parseCodeGenArgs(res.getCodeGenOpts(), args, diags);
789   success &= parseSemaArgs(res, args, diags);
790   success &= parseDialectArgs(res, args, diags);
791   success &= parseDiagArgs(res, args, diags);
792   res.frontendOpts.llvmArgs =
793       args.getAllArgValues(clang::driver::options::OPT_mllvm);
794 
795   res.frontendOpts.mlirArgs =
796       args.getAllArgValues(clang::driver::options::OPT_mmlir);
797 
798   success &= parseFloatingPointArgs(res, args, diags);
799 
800   return success;
801 }
802 
803 void CompilerInvocation::collectMacroDefinitions() {
804   auto &ppOpts = this->getPreprocessorOpts();
805 
806   for (unsigned i = 0, n = ppOpts.macros.size(); i != n; ++i) {
807     llvm::StringRef macro = ppOpts.macros[i].first;
808     bool isUndef = ppOpts.macros[i].second;
809 
810     std::pair<llvm::StringRef, llvm::StringRef> macroPair = macro.split('=');
811     llvm::StringRef macroName = macroPair.first;
812     llvm::StringRef macroBody = macroPair.second;
813 
814     // For an #undef'd macro, we only care about the name.
815     if (isUndef) {
816       parserOpts.predefinitions.emplace_back(macroName.str(),
817                                              std::optional<std::string>{});
818       continue;
819     }
820 
821     // For a #define'd macro, figure out the actual definition.
822     if (macroName.size() == macro.size())
823       macroBody = "1";
824     else {
825       // Note: GCC drops anything following an end-of-line character.
826       llvm::StringRef::size_type end = macroBody.find_first_of("\n\r");
827       macroBody = macroBody.substr(0, end);
828     }
829     parserOpts.predefinitions.emplace_back(
830         macroName, std::optional<std::string>(macroBody.str()));
831   }
832 }
833 
834 void CompilerInvocation::setDefaultFortranOpts() {
835   auto &fortranOptions = getFortranOpts();
836 
837   std::vector<std::string> searchDirectories{"."s};
838   fortranOptions.searchDirectories = searchDirectories;
839 
840   // Add the location of omp_lib.h to the search directories. Currently this is
841   // identical to the modules' directory.
842   fortranOptions.searchDirectories.emplace_back(getOpenMPHeadersDir());
843 
844   fortranOptions.isFixedForm = false;
845 }
846 
847 // TODO: When expanding this method, consider creating a dedicated API for
848 // this. Also at some point we will need to differentiate between different
849 // targets and add dedicated predefines for each.
850 void CompilerInvocation::setDefaultPredefinitions() {
851   auto &fortranOptions = getFortranOpts();
852   const auto &frontendOptions = getFrontendOpts();
853 
854   // Populate the macro list with version numbers and other predefinitions.
855   fortranOptions.predefinitions.emplace_back("__flang__", "1");
856   fortranOptions.predefinitions.emplace_back("__flang_major__",
857                                              FLANG_VERSION_MAJOR_STRING);
858   fortranOptions.predefinitions.emplace_back("__flang_minor__",
859                                              FLANG_VERSION_MINOR_STRING);
860   fortranOptions.predefinitions.emplace_back("__flang_patchlevel__",
861                                              FLANG_VERSION_PATCHLEVEL_STRING);
862 
863   // Add predefinitions based on extensions enabled
864   if (frontendOptions.features.IsEnabled(
865           Fortran::common::LanguageFeature::OpenACC)) {
866     fortranOptions.predefinitions.emplace_back("_OPENACC", "202011");
867   }
868   if (frontendOptions.features.IsEnabled(
869           Fortran::common::LanguageFeature::OpenMP)) {
870     fortranOptions.predefinitions.emplace_back("_OPENMP", "201511");
871   }
872   llvm::Triple targetTriple{llvm::Triple(this->targetOpts.triple)};
873   if (targetTriple.getArch() == llvm::Triple::ArchType::x86_64) {
874     fortranOptions.predefinitions.emplace_back("__x86_64__", "1");
875     fortranOptions.predefinitions.emplace_back("__x86_64", "1");
876   }
877 }
878 
879 void CompilerInvocation::setFortranOpts() {
880   auto &fortranOptions = getFortranOpts();
881   const auto &frontendOptions = getFrontendOpts();
882   const auto &preprocessorOptions = getPreprocessorOpts();
883   auto &moduleDirJ = getModuleDir();
884 
885   if (frontendOptions.fortranForm != FortranForm::Unknown) {
886     fortranOptions.isFixedForm =
887         frontendOptions.fortranForm == FortranForm::FixedForm;
888   }
889   fortranOptions.fixedFormColumns = frontendOptions.fixedFormColumns;
890 
891   fortranOptions.features = frontendOptions.features;
892   fortranOptions.encoding = frontendOptions.encoding;
893 
894   // Adding search directories specified by -I
895   fortranOptions.searchDirectories.insert(
896       fortranOptions.searchDirectories.end(),
897       preprocessorOptions.searchDirectoriesFromDashI.begin(),
898       preprocessorOptions.searchDirectoriesFromDashI.end());
899 
900   // Add the ordered list of -intrinsic-modules-path
901   fortranOptions.searchDirectories.insert(
902       fortranOptions.searchDirectories.end(),
903       preprocessorOptions.searchDirectoriesFromIntrModPath.begin(),
904       preprocessorOptions.searchDirectoriesFromIntrModPath.end());
905 
906   //  Add the default intrinsic module directory
907   fortranOptions.intrinsicModuleDirectories.emplace_back(getIntrinsicDir());
908 
909   // Add the directory supplied through -J/-module-dir to the list of search
910   // directories
911   if (moduleDirJ != ".")
912     fortranOptions.searchDirectories.emplace_back(moduleDirJ);
913 
914   if (frontendOptions.instrumentedParse)
915     fortranOptions.instrumentedParse = true;
916 
917   if (frontendOptions.showColors)
918     fortranOptions.showColors = true;
919 
920   if (frontendOptions.needProvenanceRangeToCharBlockMappings)
921     fortranOptions.needProvenanceRangeToCharBlockMappings = true;
922 
923   if (getEnableConformanceChecks()) {
924     fortranOptions.features.WarnOnAllNonstandard();
925   }
926 }
927 
928 void CompilerInvocation::setSemanticsOpts(
929     Fortran::parser::AllCookedSources &allCookedSources) {
930   auto &fortranOptions = getFortranOpts();
931 
932   semanticsContext = std::make_unique<semantics::SemanticsContext>(
933       getDefaultKinds(), fortranOptions.features, allCookedSources);
934 
935   semanticsContext->set_moduleDirectory(getModuleDir())
936       .set_searchDirectories(fortranOptions.searchDirectories)
937       .set_intrinsicModuleDirectories(fortranOptions.intrinsicModuleDirectories)
938       .set_warnOnNonstandardUsage(getEnableConformanceChecks())
939       .set_warningsAreErrors(getWarnAsErr())
940       .set_moduleFileSuffix(getModuleFileSuffix());
941 
942   llvm::Triple targetTriple{llvm::Triple(this->targetOpts.triple)};
943   // FIXME: Handle real(3) ?
944   if (targetTriple.getArch() != llvm::Triple::ArchType::x86_64) {
945     semanticsContext->targetCharacteristics().DisableType(
946         Fortran::common::TypeCategory::Real, /*kind=*/10);
947   }
948 }
949 
950 /// Set \p loweringOptions controlling lowering behavior based
951 /// on the \p optimizationLevel.
952 void CompilerInvocation::setLoweringOptions() {
953   const CodeGenOptions &codegenOpts = getCodeGenOpts();
954 
955   // Lower TRANSPOSE as a runtime call under -O0.
956   loweringOpts.setOptimizeTranspose(codegenOpts.OptimizationLevel > 0);
957 
958   const LangOptions &langOptions = getLangOpts();
959   Fortran::common::MathOptionsBase &mathOpts = loweringOpts.getMathOptions();
960   // TODO: when LangOptions are finalized, we can represent
961   //       the math related options using Fortran::commmon::MathOptionsBase,
962   //       so that we can just copy it into LoweringOptions.
963   mathOpts
964       .setFPContractEnabled(langOptions.getFPContractMode() ==
965                             LangOptions::FPM_Fast)
966       .setNoHonorInfs(langOptions.NoHonorInfs)
967       .setNoHonorNaNs(langOptions.NoHonorNaNs)
968       .setApproxFunc(langOptions.ApproxFunc)
969       .setNoSignedZeros(langOptions.NoSignedZeros)
970       .setAssociativeMath(langOptions.AssociativeMath)
971       .setReciprocalMath(langOptions.ReciprocalMath);
972 }
973