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 #include "flang/Frontend/CompilerInvocation.h"
10 #include "flang/Common/Fortran-features.h"
11 #include "flang/Frontend/PreprocessorOptions.h"
12 #include "flang/Frontend/TargetOptions.h"
13 #include "flang/Semantics/semantics.h"
14 #include "flang/Version.inc"
15 #include "clang/Basic/AllDiagnostics.h"
16 #include "clang/Basic/DiagnosticDriver.h"
17 #include "clang/Basic/DiagnosticOptions.h"
18 #include "clang/Driver/DriverDiagnostic.h"
19 #include "clang/Driver/Options.h"
20 #include "llvm/ADT/StringRef.h"
21 #include "llvm/ADT/StringSwitch.h"
22 #include "llvm/Option/Arg.h"
23 #include "llvm/Option/ArgList.h"
24 #include "llvm/Option/OptTable.h"
25 #include "llvm/Support/FileSystem.h"
26 #include "llvm/Support/FileUtilities.h"
27 #include "llvm/Support/Path.h"
28 #include "llvm/Support/Process.h"
29 #include "llvm/Support/raw_ostream.h"
30 #include <memory>
31 
32 using namespace Fortran::frontend;
33 
34 //===----------------------------------------------------------------------===//
35 // Initialization.
36 //===----------------------------------------------------------------------===//
37 CompilerInvocationBase::CompilerInvocationBase()
38     : diagnosticOpts_(new clang::DiagnosticOptions()),
39       preprocessorOpts_(new PreprocessorOptions()) {}
40 
41 CompilerInvocationBase::CompilerInvocationBase(const CompilerInvocationBase &x)
42     : diagnosticOpts_(new clang::DiagnosticOptions(x.GetDiagnosticOpts())),
43       preprocessorOpts_(new PreprocessorOptions(x.preprocessorOpts())) {}
44 
45 CompilerInvocationBase::~CompilerInvocationBase() = default;
46 
47 //===----------------------------------------------------------------------===//
48 // Deserialization (from args)
49 //===----------------------------------------------------------------------===//
50 static bool parseShowColorsArgs(
51     const llvm::opt::ArgList &args, bool defaultColor) {
52   // Color diagnostics default to auto ("on" if terminal supports) in the driver
53   // but default to off in cc1, needing an explicit OPT_fdiagnostics_color.
54   // Support both clang's -f[no-]color-diagnostics and gcc's
55   // -f[no-]diagnostics-colors[=never|always|auto].
56   enum {
57     Colors_On,
58     Colors_Off,
59     Colors_Auto
60   } ShowColors = defaultColor ? Colors_Auto : Colors_Off;
61 
62   for (auto *a : args) {
63     const llvm::opt::Option &O = a->getOption();
64     if (O.matches(clang::driver::options::OPT_fcolor_diagnostics) ||
65         O.matches(clang::driver::options::OPT_fdiagnostics_color)) {
66       ShowColors = Colors_On;
67     } else if (O.matches(clang::driver::options::OPT_fno_color_diagnostics) ||
68         O.matches(clang::driver::options::OPT_fno_diagnostics_color)) {
69       ShowColors = Colors_Off;
70     } else if (O.matches(clang::driver::options::OPT_fdiagnostics_color_EQ)) {
71       llvm::StringRef value(a->getValue());
72       if (value == "always")
73         ShowColors = Colors_On;
74       else if (value == "never")
75         ShowColors = Colors_Off;
76       else if (value == "auto")
77         ShowColors = Colors_Auto;
78     }
79   }
80 
81   return ShowColors == Colors_On ||
82       (ShowColors == Colors_Auto && llvm::sys::Process::StandardErrHasColors());
83 }
84 
85 bool Fortran::frontend::ParseDiagnosticArgs(clang::DiagnosticOptions &opts,
86     llvm::opt::ArgList &args, bool defaultDiagColor) {
87   opts.ShowColors = parseShowColorsArgs(args, defaultDiagColor);
88 
89   return true;
90 }
91 
92 /// Parses all target input arguments and populates the target
93 /// options accordingly.
94 ///
95 /// \param [in] opts The target options instance to update
96 /// \param [in] args The list of input arguments (from the compiler invocation)
97 static void ParseTargetArgs(TargetOptions &opts, llvm::opt::ArgList &args) {
98   opts.triple = args.getLastArgValue(clang::driver::options::OPT_triple);
99 }
100 
101 // Tweak the frontend configuration based on the frontend action
102 static void setUpFrontendBasedOnAction(FrontendOptions &opts) {
103   assert(opts.programAction != Fortran::frontend::InvalidAction &&
104       "Fortran frontend action not set!");
105 
106   if (opts.programAction == DebugDumpParsingLog)
107     opts.instrumentedParse = true;
108 
109   if (opts.programAction == DebugDumpProvenance ||
110       opts.programAction == Fortran::frontend::GetDefinition)
111     opts.needProvenanceRangeToCharBlockMappings = true;
112 }
113 
114 static bool ParseFrontendArgs(FrontendOptions &opts, llvm::opt::ArgList &args,
115     clang::DiagnosticsEngine &diags) {
116   unsigned numErrorsBefore = diags.getNumErrors();
117 
118   // By default the frontend driver creates a ParseSyntaxOnly action.
119   opts.programAction = ParseSyntaxOnly;
120 
121   // Treat multiple action options as an invocation error. Note that `clang
122   // -cc1` does accept multiple action options, but will only consider the
123   // rightmost one.
124   if (args.hasMultipleArgs(clang::driver::options::OPT_Action_Group)) {
125     const unsigned diagID = diags.getCustomDiagID(
126         clang::DiagnosticsEngine::Error, "Only one action option is allowed");
127     diags.Report(diagID);
128     return false;
129   }
130 
131   // Identify the action (i.e. opts.ProgramAction)
132   if (const llvm::opt::Arg *a =
133           args.getLastArg(clang::driver::options::OPT_Action_Group)) {
134     switch (a->getOption().getID()) {
135     default: {
136       llvm_unreachable("Invalid option in group!");
137     }
138     case clang::driver::options::OPT_test_io:
139       opts.programAction = InputOutputTest;
140       break;
141     case clang::driver::options::OPT_E:
142       opts.programAction = PrintPreprocessedInput;
143       break;
144     case clang::driver::options::OPT_fsyntax_only:
145       opts.programAction = ParseSyntaxOnly;
146       break;
147     case clang::driver::options::OPT_emit_mlir:
148       opts.programAction = EmitMLIR;
149       break;
150     case clang::driver::options::OPT_emit_llvm:
151       opts.programAction = EmitLLVM;
152       break;
153     case clang::driver::options::OPT_emit_obj:
154       opts.programAction = EmitObj;
155       break;
156     case clang::driver::options::OPT_fdebug_unparse:
157       opts.programAction = DebugUnparse;
158       break;
159     case clang::driver::options::OPT_fdebug_unparse_no_sema:
160       opts.programAction = DebugUnparseNoSema;
161       break;
162     case clang::driver::options::OPT_fdebug_unparse_with_symbols:
163       opts.programAction = DebugUnparseWithSymbols;
164       break;
165     case clang::driver::options::OPT_fdebug_dump_symbols:
166       opts.programAction = DebugDumpSymbols;
167       break;
168     case clang::driver::options::OPT_fdebug_dump_parse_tree:
169       opts.programAction = DebugDumpParseTree;
170       break;
171     case clang::driver::options::OPT_fdebug_dump_pft:
172       opts.programAction = DebugDumpPFT;
173       break;
174     case clang::driver::options::OPT_fdebug_dump_all:
175       opts.programAction = DebugDumpAll;
176       break;
177     case clang::driver::options::OPT_fdebug_dump_parse_tree_no_sema:
178       opts.programAction = DebugDumpParseTreeNoSema;
179       break;
180     case clang::driver::options::OPT_fdebug_dump_provenance:
181       opts.programAction = DebugDumpProvenance;
182       break;
183     case clang::driver::options::OPT_fdebug_dump_parsing_log:
184       opts.programAction = DebugDumpParsingLog;
185       break;
186     case clang::driver::options::OPT_fdebug_measure_parse_tree:
187       opts.programAction = DebugMeasureParseTree;
188       break;
189     case clang::driver::options::OPT_fdebug_pre_fir_tree:
190       opts.programAction = DebugPreFIRTree;
191       break;
192     case clang::driver::options::OPT_fget_symbols_sources:
193       opts.programAction = GetSymbolsSources;
194       break;
195     case clang::driver::options::OPT_fget_definition:
196       opts.programAction = GetDefinition;
197       break;
198     case clang::driver::options::OPT_init_only:
199       opts.programAction = InitOnly;
200       break;
201 
202       // TODO:
203       // case clang::driver::options::OPT_emit_llvm:
204       // case clang::driver::options::OPT_emit_llvm_only:
205       // case clang::driver::options::OPT_emit_codegen_only:
206       // case clang::driver::options::OPT_emit_module:
207       // (...)
208     }
209 
210     // Parse the values provided with `-fget-definition` (there should be 3
211     // integers)
212     if (llvm::opt::OptSpecifier(a->getOption().getID()) ==
213         clang::driver::options::OPT_fget_definition) {
214       unsigned optVals[3] = {0, 0, 0};
215 
216       for (unsigned i = 0; i < 3; i++) {
217         llvm::StringRef val = a->getValue(i);
218 
219         if (val.getAsInteger(10, optVals[i])) {
220           // A non-integer was encountered - that's an error.
221           diags.Report(clang::diag::err_drv_invalid_value)
222               << a->getOption().getName() << val;
223           break;
224         }
225       }
226       opts.getDefVals.line = optVals[0];
227       opts.getDefVals.startColumn = optVals[1];
228       opts.getDefVals.endColumn = optVals[2];
229     }
230   }
231 
232   // Parsing -load <dsopath> option and storing shared object path
233   if (llvm::opt::Arg *a = args.getLastArg(clang::driver::options::OPT_load)) {
234     opts.plugins.push_back(a->getValue());
235   }
236 
237   // Parsing -plugin <name> option and storing plugin name and setting action
238   if (const llvm::opt::Arg *a =
239           args.getLastArg(clang::driver::options::OPT_plugin)) {
240     opts.programAction = PluginAction;
241     opts.ActionName = a->getValue();
242   }
243 
244   opts.outputFile = args.getLastArgValue(clang::driver::options::OPT_o);
245   opts.showHelp = args.hasArg(clang::driver::options::OPT_help);
246   opts.showVersion = args.hasArg(clang::driver::options::OPT_version);
247 
248   // Get the input kind (from the value passed via `-x`)
249   InputKind dashX(Language::Unknown);
250   if (const llvm::opt::Arg *a =
251           args.getLastArg(clang::driver::options::OPT_x)) {
252     llvm::StringRef XValue = a->getValue();
253     // Principal languages.
254     dashX = llvm::StringSwitch<InputKind>(XValue)
255                 .Case("f90", Language::Fortran)
256                 .Default(Language::Unknown);
257 
258     // Some special cases cannot be combined with suffixes.
259     if (dashX.IsUnknown())
260       dashX = llvm::StringSwitch<InputKind>(XValue)
261                   .Case("ir", Language::LLVM_IR)
262                   .Default(Language::Unknown);
263 
264     if (dashX.IsUnknown())
265       diags.Report(clang::diag::err_drv_invalid_value)
266           << a->getAsString(args) << a->getValue();
267   }
268 
269   // Collect the input files and save them in our instance of FrontendOptions.
270   std::vector<std::string> inputs =
271       args.getAllArgValues(clang::driver::options::OPT_INPUT);
272   opts.inputs.clear();
273   if (inputs.empty())
274     // '-' is the default input if none is given.
275     inputs.push_back("-");
276   for (unsigned i = 0, e = inputs.size(); i != e; ++i) {
277     InputKind ik = dashX;
278     if (ik.IsUnknown()) {
279       ik = FrontendOptions::GetInputKindForExtension(
280           llvm::StringRef(inputs[i]).rsplit('.').second);
281       if (ik.IsUnknown())
282         ik = Language::Unknown;
283       if (i == 0)
284         dashX = ik;
285     }
286 
287     opts.inputs.emplace_back(std::move(inputs[i]), ik);
288   }
289 
290   // Set fortranForm based on options -ffree-form and -ffixed-form.
291   if (const auto *arg = args.getLastArg(clang::driver::options::OPT_ffixed_form,
292           clang::driver::options::OPT_ffree_form)) {
293     opts.fortranForm =
294         arg->getOption().matches(clang::driver::options::OPT_ffixed_form)
295         ? FortranForm::FixedForm
296         : FortranForm::FreeForm;
297   }
298 
299   // Set fixedFormColumns based on -ffixed-line-length=<value>
300   if (const auto *arg =
301           args.getLastArg(clang::driver::options::OPT_ffixed_line_length_EQ)) {
302     llvm::StringRef argValue = llvm::StringRef(arg->getValue());
303     std::int64_t columns = -1;
304     if (argValue == "none") {
305       columns = 0;
306     } else if (argValue.getAsInteger(/*Radix=*/10, columns)) {
307       columns = -1;
308     }
309     if (columns < 0) {
310       diags.Report(clang::diag::err_drv_negative_columns)
311           << arg->getOption().getName() << arg->getValue();
312     } else if (columns == 0) {
313       opts.fixedFormColumns = 1000000;
314     } else if (columns < 7) {
315       diags.Report(clang::diag::err_drv_small_columns)
316           << arg->getOption().getName() << arg->getValue() << "7";
317     } else {
318       opts.fixedFormColumns = columns;
319     }
320   }
321 
322   // -f{no-}implicit-none
323   opts.features.Enable(
324       Fortran::common::LanguageFeature::ImplicitNoneTypeAlways,
325       args.hasFlag(clang::driver::options::OPT_fimplicit_none,
326           clang::driver::options::OPT_fno_implicit_none, false));
327 
328   // -f{no-}backslash
329   opts.features.Enable(Fortran::common::LanguageFeature::BackslashEscapes,
330       args.hasFlag(clang::driver::options::OPT_fbackslash,
331           clang::driver::options::OPT_fno_backslash, false));
332 
333   // -f{no-}logical-abbreviations
334   opts.features.Enable(Fortran::common::LanguageFeature::LogicalAbbreviations,
335       args.hasFlag(clang::driver::options::OPT_flogical_abbreviations,
336           clang::driver::options::OPT_fno_logical_abbreviations, false));
337 
338   // -f{no-}xor-operator
339   opts.features.Enable(Fortran::common::LanguageFeature::XOROperator,
340       args.hasFlag(clang::driver::options::OPT_fxor_operator,
341           clang::driver::options::OPT_fno_xor_operator, false));
342 
343   // -fno-automatic
344   if (args.hasArg(clang::driver::options::OPT_fno_automatic)) {
345     opts.features.Enable(Fortran::common::LanguageFeature::DefaultSave);
346   }
347 
348   if (args.hasArg(
349           clang::driver::options::OPT_falternative_parameter_statement)) {
350     opts.features.Enable(Fortran::common::LanguageFeature::OldStyleParameter);
351   }
352   if (const llvm::opt::Arg *arg =
353           args.getLastArg(clang::driver::options::OPT_finput_charset_EQ)) {
354     llvm::StringRef argValue = arg->getValue();
355     if (argValue == "utf-8") {
356       opts.encoding = Fortran::parser::Encoding::UTF_8;
357     } else if (argValue == "latin-1") {
358       opts.encoding = Fortran::parser::Encoding::LATIN_1;
359     } else {
360       diags.Report(clang::diag::err_drv_invalid_value)
361           << arg->getAsString(args) << argValue;
362     }
363   }
364 
365   setUpFrontendBasedOnAction(opts);
366   opts.dashX = dashX;
367 
368   return diags.getNumErrors() == numErrorsBefore;
369 }
370 
371 // Generate the path to look for intrinsic modules
372 static std::string getIntrinsicDir() {
373   // TODO: Find a system independent API
374   llvm::SmallString<128> driverPath;
375   driverPath.assign(llvm::sys::fs::getMainExecutable(nullptr, nullptr));
376   llvm::sys::path::remove_filename(driverPath);
377   driverPath.append("/../include/flang/");
378   return std::string(driverPath);
379 }
380 
381 /// Parses all preprocessor input arguments and populates the preprocessor
382 /// options accordingly.
383 ///
384 /// \param [in] opts The preprocessor options instance
385 /// \param [out] args The list of input arguments
386 static void parsePreprocessorArgs(
387     Fortran::frontend::PreprocessorOptions &opts, llvm::opt::ArgList &args) {
388   // Add macros from the command line.
389   for (const auto *currentArg : args.filtered(
390            clang::driver::options::OPT_D, clang::driver::options::OPT_U)) {
391     if (currentArg->getOption().matches(clang::driver::options::OPT_D)) {
392       opts.addMacroDef(currentArg->getValue());
393     } else {
394       opts.addMacroUndef(currentArg->getValue());
395     }
396   }
397 
398   // Add the ordered list of -I's.
399   for (const auto *currentArg : args.filtered(clang::driver::options::OPT_I))
400     opts.searchDirectoriesFromDashI.emplace_back(currentArg->getValue());
401 
402   // Prepend the ordered list of -intrinsic-modules-path
403   // to the default location to search.
404   for (const auto *currentArg :
405       args.filtered(clang::driver::options::OPT_fintrinsic_modules_path))
406     opts.searchDirectoriesFromIntrModPath.emplace_back(currentArg->getValue());
407 
408   // -cpp/-nocpp
409   if (const auto *currentArg = args.getLastArg(
410           clang::driver::options::OPT_cpp, clang::driver::options::OPT_nocpp))
411     opts.macrosFlag =
412         (currentArg->getOption().matches(clang::driver::options::OPT_cpp))
413         ? PPMacrosFlag::Include
414         : PPMacrosFlag::Exclude;
415 
416   opts.noReformat = args.hasArg(clang::driver::options::OPT_fno_reformat);
417   opts.noLineDirectives = args.hasArg(clang::driver::options::OPT_P);
418 }
419 
420 /// Parses all semantic related arguments and populates the variables
421 /// options accordingly. Returns false if new errors are generated.
422 static bool parseSemaArgs(CompilerInvocation &res, llvm::opt::ArgList &args,
423     clang::DiagnosticsEngine &diags) {
424   unsigned numErrorsBefore = diags.getNumErrors();
425 
426   // -J/module-dir option
427   auto moduleDirList =
428       args.getAllArgValues(clang::driver::options::OPT_module_dir);
429   // User can only specify -J/-module-dir once
430   // https://gcc.gnu.org/onlinedocs/gfortran/Directory-Options.html
431   if (moduleDirList.size() > 1) {
432     const unsigned diagID =
433         diags.getCustomDiagID(clang::DiagnosticsEngine::Error,
434             "Only one '-module-dir/-J' option allowed");
435     diags.Report(diagID);
436   }
437   if (moduleDirList.size() == 1)
438     res.SetModuleDir(moduleDirList[0]);
439 
440   // -fdebug-module-writer option
441   if (args.hasArg(clang::driver::options::OPT_fdebug_module_writer)) {
442     res.SetDebugModuleDir(true);
443   }
444 
445   // -module-suffix
446   if (const auto *moduleSuffix =
447           args.getLastArg(clang::driver::options::OPT_module_suffix)) {
448     res.SetModuleFileSuffix(moduleSuffix->getValue());
449   }
450 
451   // -f{no-}analyzed-objects-for-unparse
452   res.SetUseAnalyzedObjectsForUnparse(
453       args.hasFlag(clang::driver::options::OPT_fanalyzed_objects_for_unparse,
454           clang::driver::options::OPT_fno_analyzed_objects_for_unparse, true));
455 
456   return diags.getNumErrors() == numErrorsBefore;
457 }
458 
459 /// Parses all diagnostics related arguments and populates the variables
460 /// options accordingly. Returns false if new errors are generated.
461 static bool parseDiagArgs(CompilerInvocation &res, llvm::opt::ArgList &args,
462     clang::DiagnosticsEngine &diags) {
463   unsigned numErrorsBefore = diags.getNumErrors();
464 
465   // -Werror option
466   // TODO: Currently throws a Diagnostic for anything other than -W<error>,
467   // this has to change when other -W<opt>'s are supported.
468   if (args.hasArg(clang::driver::options::OPT_W_Joined)) {
469     if (args.getLastArgValue(clang::driver::options::OPT_W_Joined)
470             .equals("error")) {
471       res.SetWarnAsErr(true);
472     } else {
473       const unsigned diagID =
474           diags.getCustomDiagID(clang::DiagnosticsEngine::Error,
475               "Only `-Werror` is supported currently.");
476       diags.Report(diagID);
477     }
478   }
479 
480   return diags.getNumErrors() == numErrorsBefore;
481 }
482 
483 /// Parses all Dialect related arguments and populates the variables
484 /// options accordingly. Returns false if new errors are generated.
485 static bool parseDialectArgs(CompilerInvocation &res, llvm::opt::ArgList &args,
486     clang::DiagnosticsEngine &diags) {
487   unsigned numErrorsBefore = diags.getNumErrors();
488 
489   // -fdefault* family
490   if (args.hasArg(clang::driver::options::OPT_fdefault_real_8)) {
491     res.defaultKinds().set_defaultRealKind(8);
492     res.defaultKinds().set_doublePrecisionKind(16);
493   }
494   if (args.hasArg(clang::driver::options::OPT_fdefault_integer_8)) {
495     res.defaultKinds().set_defaultIntegerKind(8);
496     res.defaultKinds().set_subscriptIntegerKind(8);
497     res.defaultKinds().set_sizeIntegerKind(8);
498   }
499   if (args.hasArg(clang::driver::options::OPT_fdefault_double_8)) {
500     if (!args.hasArg(clang::driver::options::OPT_fdefault_real_8)) {
501       // -fdefault-double-8 has to be used with -fdefault-real-8
502       // to be compatible with gfortran
503       const unsigned diagID =
504           diags.getCustomDiagID(clang::DiagnosticsEngine::Error,
505               "Use of `-fdefault-double-8` requires `-fdefault-real-8`");
506       diags.Report(diagID);
507     }
508     // https://gcc.gnu.org/onlinedocs/gfortran/Fortran-Dialect-Options.html
509     res.defaultKinds().set_doublePrecisionKind(8);
510   }
511   if (args.hasArg(clang::driver::options::OPT_flarge_sizes))
512     res.defaultKinds().set_sizeIntegerKind(8);
513 
514   // -fopenmp and -fopenacc
515   if (args.hasArg(clang::driver::options::OPT_fopenacc)) {
516     res.frontendOpts().features.Enable(
517         Fortran::common::LanguageFeature::OpenACC);
518   }
519   if (args.hasArg(clang::driver::options::OPT_fopenmp)) {
520     res.frontendOpts().features.Enable(
521         Fortran::common::LanguageFeature::OpenMP);
522   }
523 
524   // -pedantic
525   if (args.hasArg(clang::driver::options::OPT_pedantic)) {
526     res.set_EnableConformanceChecks();
527   }
528   // -std=f2018 (currently this implies -pedantic)
529   // TODO: Set proper options when more fortran standards
530   // are supported.
531   if (args.hasArg(clang::driver::options::OPT_std_EQ)) {
532     auto standard = args.getLastArgValue(clang::driver::options::OPT_std_EQ);
533     // We only allow f2018 as the given standard
534     if (standard.equals("f2018")) {
535       res.set_EnableConformanceChecks();
536     } else {
537       const unsigned diagID =
538           diags.getCustomDiagID(clang::DiagnosticsEngine::Error,
539               "Only -std=f2018 is allowed currently.");
540       diags.Report(diagID);
541     }
542   }
543   return diags.getNumErrors() == numErrorsBefore;
544 }
545 
546 bool CompilerInvocation::CreateFromArgs(CompilerInvocation &res,
547     llvm::ArrayRef<const char *> commandLineArgs,
548     clang::DiagnosticsEngine &diags) {
549 
550   bool success = true;
551 
552   // Parse the arguments
553   const llvm::opt::OptTable &opts = clang::driver::getDriverOptTable();
554   const unsigned includedFlagsBitmask = clang::driver::options::FC1Option;
555   unsigned missingArgIndex, missingArgCount;
556   llvm::opt::InputArgList args = opts.ParseArgs(
557       commandLineArgs, missingArgIndex, missingArgCount, includedFlagsBitmask);
558 
559   // Check for missing argument error.
560   if (missingArgCount) {
561     diags.Report(clang::diag::err_drv_missing_argument)
562         << args.getArgString(missingArgIndex) << missingArgCount;
563     success = false;
564   }
565 
566   // Issue errors on unknown arguments
567   for (const auto *a : args.filtered(clang::driver::options::OPT_UNKNOWN)) {
568     auto argString = a->getAsString(args);
569     std::string nearest;
570     if (opts.findNearest(argString, nearest, includedFlagsBitmask) > 1)
571       diags.Report(clang::diag::err_drv_unknown_argument) << argString;
572     else
573       diags.Report(clang::diag::err_drv_unknown_argument_with_suggestion)
574           << argString << nearest;
575     success = false;
576   }
577 
578   success &= ParseFrontendArgs(res.frontendOpts(), args, diags);
579   ParseTargetArgs(res.targetOpts(), args);
580   parsePreprocessorArgs(res.preprocessorOpts(), args);
581   success &= parseSemaArgs(res, args, diags);
582   success &= parseDialectArgs(res, args, diags);
583   success &= parseDiagArgs(res, args, diags);
584 
585   return success;
586 }
587 
588 void CompilerInvocation::CollectMacroDefinitions() {
589   auto &ppOpts = this->preprocessorOpts();
590 
591   for (unsigned i = 0, n = ppOpts.macros.size(); i != n; ++i) {
592     llvm::StringRef macro = ppOpts.macros[i].first;
593     bool isUndef = ppOpts.macros[i].second;
594 
595     std::pair<llvm::StringRef, llvm::StringRef> macroPair = macro.split('=');
596     llvm::StringRef macroName = macroPair.first;
597     llvm::StringRef macroBody = macroPair.second;
598 
599     // For an #undef'd macro, we only care about the name.
600     if (isUndef) {
601       parserOpts_.predefinitions.emplace_back(
602           macroName.str(), std::optional<std::string>{});
603       continue;
604     }
605 
606     // For a #define'd macro, figure out the actual definition.
607     if (macroName.size() == macro.size())
608       macroBody = "1";
609     else {
610       // Note: GCC drops anything following an end-of-line character.
611       llvm::StringRef::size_type End = macroBody.find_first_of("\n\r");
612       macroBody = macroBody.substr(0, End);
613     }
614     parserOpts_.predefinitions.emplace_back(
615         macroName, std::optional<std::string>(macroBody.str()));
616   }
617 }
618 
619 void CompilerInvocation::SetDefaultFortranOpts() {
620   auto &fortranOptions = fortranOpts();
621 
622   std::vector<std::string> searchDirectories{"."s};
623   fortranOptions.searchDirectories = searchDirectories;
624   fortranOptions.isFixedForm = false;
625 }
626 
627 // TODO: When expanding this method, consider creating a dedicated API for
628 // this. Also at some point we will need to differentiate between different
629 // targets and add dedicated predefines for each.
630 void CompilerInvocation::SetDefaultPredefinitions() {
631   auto &fortranOptions = fortranOpts();
632   const auto &frontendOptions = frontendOpts();
633 
634   // Populate the macro list with version numbers and other predefinitions.
635   fortranOptions.predefinitions.emplace_back("__flang__", "1");
636   fortranOptions.predefinitions.emplace_back(
637       "__flang_major__", FLANG_VERSION_MAJOR_STRING);
638   fortranOptions.predefinitions.emplace_back(
639       "__flang_minor__", FLANG_VERSION_MINOR_STRING);
640   fortranOptions.predefinitions.emplace_back(
641       "__flang_patchlevel__", FLANG_VERSION_PATCHLEVEL_STRING);
642 
643   // Add predefinitions based on extensions enabled
644   if (frontendOptions.features.IsEnabled(
645           Fortran::common::LanguageFeature::OpenACC)) {
646     fortranOptions.predefinitions.emplace_back("_OPENACC", "202011");
647   }
648   if (frontendOptions.features.IsEnabled(
649           Fortran::common::LanguageFeature::OpenMP)) {
650     fortranOptions.predefinitions.emplace_back("_OPENMP", "201511");
651   }
652 }
653 
654 void CompilerInvocation::SetFortranOpts() {
655   auto &fortranOptions = fortranOpts();
656   const auto &frontendOptions = frontendOpts();
657   const auto &preprocessorOptions = preprocessorOpts();
658   auto &moduleDirJ = moduleDir();
659 
660   if (frontendOptions.fortranForm != FortranForm::Unknown) {
661     fortranOptions.isFixedForm =
662         frontendOptions.fortranForm == FortranForm::FixedForm;
663   }
664   fortranOptions.fixedFormColumns = frontendOptions.fixedFormColumns;
665 
666   fortranOptions.features = frontendOptions.features;
667   fortranOptions.encoding = frontendOptions.encoding;
668 
669   // Adding search directories specified by -I
670   fortranOptions.searchDirectories.insert(
671       fortranOptions.searchDirectories.end(),
672       preprocessorOptions.searchDirectoriesFromDashI.begin(),
673       preprocessorOptions.searchDirectoriesFromDashI.end());
674 
675   // Add the ordered list of -intrinsic-modules-path
676   fortranOptions.searchDirectories.insert(
677       fortranOptions.searchDirectories.end(),
678       preprocessorOptions.searchDirectoriesFromIntrModPath.begin(),
679       preprocessorOptions.searchDirectoriesFromIntrModPath.end());
680 
681   //  Add the default intrinsic module directory
682   fortranOptions.intrinsicModuleDirectories.emplace_back(getIntrinsicDir());
683 
684   // Add the directory supplied through -J/-module-dir to the list of search
685   // directories
686   if (moduleDirJ.compare(".") != 0)
687     fortranOptions.searchDirectories.emplace_back(moduleDirJ);
688 
689   if (frontendOptions.instrumentedParse)
690     fortranOptions.instrumentedParse = true;
691 
692   if (frontendOptions.needProvenanceRangeToCharBlockMappings)
693     fortranOptions.needProvenanceRangeToCharBlockMappings = true;
694 
695   if (enableConformanceChecks()) {
696     fortranOptions.features.WarnOnAllNonstandard();
697   }
698 }
699 
700 void CompilerInvocation::SetSemanticsOpts(
701     Fortran::parser::AllCookedSources &allCookedSources) {
702   const auto &fortranOptions = fortranOpts();
703 
704   semanticsContext_ = std::make_unique<semantics::SemanticsContext>(
705       defaultKinds(), fortranOptions.features, allCookedSources);
706 
707   semanticsContext_->set_moduleDirectory(moduleDir())
708       .set_searchDirectories(fortranOptions.searchDirectories)
709       .set_intrinsicModuleDirectories(fortranOptions.intrinsicModuleDirectories)
710       .set_warnOnNonstandardUsage(enableConformanceChecks())
711       .set_warningsAreErrors(warnAsErr())
712       .set_moduleFileSuffix(moduleFileSuffix());
713 }
714