xref: /llvm-project/flang/lib/Frontend/CompilerInvocation.cpp (revision 8cac995eadebbf23b10f8cebc9a42adcf91cc26b)
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/Common/OpenMP-features.h"
16 #include "flang/Common/Version.h"
17 #include "flang/Frontend/CodeGenOptions.h"
18 #include "flang/Frontend/PreprocessorOptions.h"
19 #include "flang/Frontend/TargetOptions.h"
20 #include "flang/Semantics/semantics.h"
21 #include "flang/Tools/TargetSetup.h"
22 #include "flang/Version.inc"
23 #include "clang/Basic/AllDiagnostics.h"
24 #include "clang/Basic/DiagnosticDriver.h"
25 #include "clang/Basic/DiagnosticOptions.h"
26 #include "clang/Driver/DriverDiagnostic.h"
27 #include "clang/Driver/OptionUtils.h"
28 #include "clang/Driver/Options.h"
29 #include "llvm/ADT/StringRef.h"
30 #include "llvm/ADT/StringSwitch.h"
31 #include "llvm/Frontend/Debug/Options.h"
32 #include "llvm/Option/Arg.h"
33 #include "llvm/Option/ArgList.h"
34 #include "llvm/Option/OptTable.h"
35 #include "llvm/Support/FileSystem.h"
36 #include "llvm/Support/FileUtilities.h"
37 #include "llvm/Support/Path.h"
38 #include "llvm/Support/Process.h"
39 #include "llvm/Support/raw_ostream.h"
40 #include "llvm/TargetParser/Host.h"
41 #include "llvm/TargetParser/Triple.h"
42 #include <cstdlib>
43 #include <memory>
44 #include <optional>
45 
46 using namespace Fortran::frontend;
47 
48 //===----------------------------------------------------------------------===//
49 // Initialization.
50 //===----------------------------------------------------------------------===//
51 CompilerInvocationBase::CompilerInvocationBase()
52     : diagnosticOpts(new clang::DiagnosticOptions()),
53       preprocessorOpts(new PreprocessorOptions()) {}
54 
55 CompilerInvocationBase::CompilerInvocationBase(const CompilerInvocationBase &x)
56     : diagnosticOpts(new clang::DiagnosticOptions(x.getDiagnosticOpts())),
57       preprocessorOpts(new PreprocessorOptions(x.getPreprocessorOpts())) {}
58 
59 CompilerInvocationBase::~CompilerInvocationBase() = default;
60 
61 //===----------------------------------------------------------------------===//
62 // Deserialization (from args)
63 //===----------------------------------------------------------------------===//
64 static bool parseShowColorsArgs(const llvm::opt::ArgList &args,
65                                 bool defaultColor = true) {
66   // Color diagnostics default to auto ("on" if terminal supports) in the
67   // compiler driver `flang-new` but default to off in the frontend driver
68   // `flang-new -fc1`, needing an explicit OPT_fdiagnostics_color.
69   // Support both clang's -f[no-]color-diagnostics and gcc's
70   // -f[no-]diagnostics-colors[=never|always|auto].
71   enum {
72     Colors_On,
73     Colors_Off,
74     Colors_Auto
75   } showColors = defaultColor ? Colors_Auto : Colors_Off;
76 
77   for (auto *a : args) {
78     const llvm::opt::Option &opt = a->getOption();
79     if (opt.matches(clang::driver::options::OPT_fcolor_diagnostics)) {
80       showColors = Colors_On;
81     } else if (opt.matches(clang::driver::options::OPT_fno_color_diagnostics)) {
82       showColors = Colors_Off;
83     } else if (opt.matches(clang::driver::options::OPT_fdiagnostics_color_EQ)) {
84       llvm::StringRef value(a->getValue());
85       if (value == "always")
86         showColors = Colors_On;
87       else if (value == "never")
88         showColors = Colors_Off;
89       else if (value == "auto")
90         showColors = Colors_Auto;
91     }
92   }
93 
94   return showColors == Colors_On ||
95          (showColors == Colors_Auto &&
96           llvm::sys::Process::StandardErrHasColors());
97 }
98 
99 /// Extracts the optimisation level from \a args.
100 static unsigned getOptimizationLevel(llvm::opt::ArgList &args,
101                                      clang::DiagnosticsEngine &diags) {
102   unsigned defaultOpt = 0;
103 
104   if (llvm::opt::Arg *a =
105           args.getLastArg(clang::driver::options::OPT_O_Group)) {
106     if (a->getOption().matches(clang::driver::options::OPT_O0))
107       return 0;
108 
109     assert(a->getOption().matches(clang::driver::options::OPT_O));
110 
111     return getLastArgIntValue(args, clang::driver::options::OPT_O, defaultOpt,
112                               diags);
113   }
114 
115   return defaultOpt;
116 }
117 
118 bool Fortran::frontend::parseDiagnosticArgs(clang::DiagnosticOptions &opts,
119                                             llvm::opt::ArgList &args) {
120   opts.ShowColors = parseShowColorsArgs(args);
121 
122   return true;
123 }
124 
125 static bool parseDebugArgs(Fortran::frontend::CodeGenOptions &opts,
126                            llvm::opt::ArgList &args,
127                            clang::DiagnosticsEngine &diags) {
128   using DebugInfoKind = llvm::codegenoptions::DebugInfoKind;
129   if (llvm::opt::Arg *arg =
130           args.getLastArg(clang::driver::options::OPT_debug_info_kind_EQ)) {
131     std::optional<DebugInfoKind> val =
132         llvm::StringSwitch<std::optional<DebugInfoKind>>(arg->getValue())
133             .Case("line-tables-only", llvm::codegenoptions::DebugLineTablesOnly)
134             .Case("line-directives-only",
135                   llvm::codegenoptions::DebugDirectivesOnly)
136             .Case("constructor", llvm::codegenoptions::DebugInfoConstructor)
137             .Case("limited", llvm::codegenoptions::LimitedDebugInfo)
138             .Case("standalone", llvm::codegenoptions::FullDebugInfo)
139             .Case("unused-types", llvm::codegenoptions::UnusedTypeInfo)
140             .Default(std::nullopt);
141     if (!val.has_value()) {
142       diags.Report(clang::diag::err_drv_invalid_value)
143           << arg->getAsString(args) << arg->getValue();
144       return false;
145     }
146     opts.setDebugInfo(val.value());
147     if (val != llvm::codegenoptions::DebugLineTablesOnly &&
148         val != llvm::codegenoptions::NoDebugInfo) {
149       const auto debugWarning = diags.getCustomDiagID(
150           clang::DiagnosticsEngine::Warning, "Unsupported debug option: %0");
151       diags.Report(debugWarning) << arg->getValue();
152     }
153   }
154   return true;
155 }
156 
157 static bool parseVectorLibArg(Fortran::frontend::CodeGenOptions &opts,
158                               llvm::opt::ArgList &args,
159                               clang::DiagnosticsEngine &diags) {
160   llvm::opt::Arg *arg = args.getLastArg(clang::driver::options::OPT_fveclib);
161   if (!arg)
162     return true;
163 
164   using VectorLibrary = llvm::driver::VectorLibrary;
165   std::optional<VectorLibrary> val =
166       llvm::StringSwitch<std::optional<VectorLibrary>>(arg->getValue())
167           .Case("Accelerate", VectorLibrary::Accelerate)
168           .Case("LIBMVEC", VectorLibrary::LIBMVEC)
169           .Case("MASSV", VectorLibrary::MASSV)
170           .Case("SVML", VectorLibrary::SVML)
171           .Case("SLEEF", VectorLibrary::SLEEF)
172           .Case("Darwin_libsystem_m", VectorLibrary::Darwin_libsystem_m)
173           .Case("ArmPL", VectorLibrary::ArmPL)
174           .Case("NoLibrary", VectorLibrary::NoLibrary)
175           .Default(std::nullopt);
176   if (!val.has_value()) {
177     diags.Report(clang::diag::err_drv_invalid_value)
178         << arg->getAsString(args) << arg->getValue();
179     return false;
180   }
181   opts.setVecLib(val.value());
182   return true;
183 }
184 
185 // Generate an OptRemark object containing info on if the -Rgroup
186 // specified is enabled or not.
187 static CodeGenOptions::OptRemark
188 parseOptimizationRemark(clang::DiagnosticsEngine &diags,
189                         llvm::opt::ArgList &args, llvm::opt::OptSpecifier optEq,
190                         llvm::StringRef remarkOptName) {
191   assert((remarkOptName == "pass" || remarkOptName == "pass-missed" ||
192           remarkOptName == "pass-analysis") &&
193          "Unsupported remark option name provided.");
194   CodeGenOptions::OptRemark result;
195 
196   for (llvm::opt::Arg *a : args) {
197     if (a->getOption().matches(clang::driver::options::OPT_R_Joined)) {
198       llvm::StringRef value = a->getValue();
199 
200       if (value == remarkOptName) {
201         result.Kind = CodeGenOptions::RemarkKind::RK_Enabled;
202         // Enable everything
203         result.Pattern = ".*";
204         result.Regex = std::make_shared<llvm::Regex>(result.Pattern);
205 
206       } else if (value.split('-') ==
207                  std::make_pair(llvm::StringRef("no"), remarkOptName)) {
208         result.Kind = CodeGenOptions::RemarkKind::RK_Disabled;
209         // Disable everything
210         result.Pattern = "";
211         result.Regex = nullptr;
212       }
213     } else if (a->getOption().matches(optEq)) {
214       result.Kind = CodeGenOptions::RemarkKind::RK_WithPattern;
215       result.Pattern = a->getValue();
216       result.Regex = std::make_shared<llvm::Regex>(result.Pattern);
217       std::string regexError;
218 
219       if (!result.Regex->isValid(regexError)) {
220         diags.Report(clang::diag::err_drv_optimization_remark_pattern)
221             << regexError << a->getAsString(args);
222         return CodeGenOptions::OptRemark();
223       }
224     }
225   }
226   return result;
227 }
228 
229 static void parseCodeGenArgs(Fortran::frontend::CodeGenOptions &opts,
230                              llvm::opt::ArgList &args,
231                              clang::DiagnosticsEngine &diags) {
232   opts.OptimizationLevel = getOptimizationLevel(args, diags);
233 
234   if (args.hasFlag(clang::driver::options::OPT_fdebug_pass_manager,
235                    clang::driver::options::OPT_fno_debug_pass_manager, false))
236     opts.DebugPassManager = 1;
237 
238   if (args.hasFlag(clang::driver::options::OPT_fstack_arrays,
239                    clang::driver::options::OPT_fno_stack_arrays, false))
240     opts.StackArrays = 1;
241 
242   if (args.hasFlag(clang::driver::options::OPT_floop_versioning,
243                    clang::driver::options::OPT_fno_loop_versioning, false))
244     opts.LoopVersioning = 1;
245 
246   opts.AliasAnalysis = opts.OptimizationLevel > 0;
247 
248   // -mframe-pointer=none/non-leaf/all option.
249   if (const llvm::opt::Arg *a =
250           args.getLastArg(clang::driver::options::OPT_mframe_pointer_EQ)) {
251     std::optional<llvm::FramePointerKind> val =
252         llvm::StringSwitch<std::optional<llvm::FramePointerKind>>(a->getValue())
253             .Case("none", llvm::FramePointerKind::None)
254             .Case("non-leaf", llvm::FramePointerKind::NonLeaf)
255             .Case("all", llvm::FramePointerKind::All)
256             .Default(std::nullopt);
257 
258     if (!val.has_value()) {
259       diags.Report(clang::diag::err_drv_invalid_value)
260           << a->getAsString(args) << a->getValue();
261     } else
262       opts.setFramePointer(val.value());
263   }
264 
265   for (auto *a : args.filtered(clang::driver::options::OPT_fpass_plugin_EQ))
266     opts.LLVMPassPlugins.push_back(a->getValue());
267 
268   // -fembed-offload-object option
269   for (auto *a :
270        args.filtered(clang::driver::options::OPT_fembed_offload_object_EQ))
271     opts.OffloadObjects.push_back(a->getValue());
272 
273   // -flto=full/thin option.
274   if (const llvm::opt::Arg *a =
275           args.getLastArg(clang::driver::options::OPT_flto_EQ)) {
276     llvm::StringRef s = a->getValue();
277     assert((s == "full" || s == "thin") && "Unknown LTO mode.");
278     if (s == "full")
279       opts.PrepareForFullLTO = true;
280     else
281       opts.PrepareForThinLTO = true;
282   }
283 
284   if (const llvm::opt::Arg *a = args.getLastArg(
285           clang::driver::options::OPT_mcode_object_version_EQ)) {
286     llvm::StringRef s = a->getValue();
287     if (s == "5")
288       opts.CodeObjectVersion = llvm::CodeObjectVersionKind::COV_5;
289     if (s == "4")
290       opts.CodeObjectVersion = llvm::CodeObjectVersionKind::COV_4;
291     if (s == "none")
292       opts.CodeObjectVersion = llvm::CodeObjectVersionKind::COV_None;
293   }
294 
295   // -f[no-]save-optimization-record[=<format>]
296   if (const llvm::opt::Arg *a =
297           args.getLastArg(clang::driver::options::OPT_opt_record_file))
298     opts.OptRecordFile = a->getValue();
299 
300   // Optimization file format. Defaults to yaml
301   if (const llvm::opt::Arg *a =
302           args.getLastArg(clang::driver::options::OPT_opt_record_format))
303     opts.OptRecordFormat = a->getValue();
304 
305   // Specifies, using a regex, which successful optimization passes(middle and
306   // backend), to include in the final optimization record file generated. If
307   // not provided -fsave-optimization-record will include all passes.
308   if (const llvm::opt::Arg *a =
309           args.getLastArg(clang::driver::options::OPT_opt_record_passes))
310     opts.OptRecordPasses = a->getValue();
311 
312   // Create OptRemark that allows printing of all successful optimization
313   // passes applied.
314   opts.OptimizationRemark =
315       parseOptimizationRemark(diags, args, clang::driver::options::OPT_Rpass_EQ,
316                               /*remarkOptName=*/"pass");
317 
318   // Create OptRemark that allows all missed optimization passes to be printed.
319   opts.OptimizationRemarkMissed = parseOptimizationRemark(
320       diags, args, clang::driver::options::OPT_Rpass_missed_EQ,
321       /*remarkOptName=*/"pass-missed");
322 
323   // Create OptRemark that allows all optimization decisions made by LLVM
324   // to be printed.
325   opts.OptimizationRemarkAnalysis = parseOptimizationRemark(
326       diags, args, clang::driver::options::OPT_Rpass_analysis_EQ,
327       /*remarkOptName=*/"pass-analysis");
328 
329   if (opts.getDebugInfo() == llvm::codegenoptions::NoDebugInfo) {
330     // If the user requested a flag that requires source locations available in
331     // the backend, make sure that the backend tracks source location
332     // information.
333     bool needLocTracking = !opts.OptRecordFile.empty() ||
334                            !opts.OptRecordPasses.empty() ||
335                            !opts.OptRecordFormat.empty() ||
336                            opts.OptimizationRemark.hasValidPattern() ||
337                            opts.OptimizationRemarkMissed.hasValidPattern() ||
338                            opts.OptimizationRemarkAnalysis.hasValidPattern();
339 
340     if (needLocTracking)
341       opts.setDebugInfo(llvm::codegenoptions::LocTrackingOnly);
342   }
343 
344   if (auto *a = args.getLastArg(clang::driver::options::OPT_save_temps_EQ))
345     opts.SaveTempsDir = a->getValue();
346 
347   // -mrelocation-model option.
348   if (const llvm::opt::Arg *a =
349           args.getLastArg(clang::driver::options::OPT_mrelocation_model)) {
350     llvm::StringRef modelName = a->getValue();
351     auto relocModel =
352         llvm::StringSwitch<std::optional<llvm::Reloc::Model>>(modelName)
353             .Case("static", llvm::Reloc::Static)
354             .Case("pic", llvm::Reloc::PIC_)
355             .Case("dynamic-no-pic", llvm::Reloc::DynamicNoPIC)
356             .Case("ropi", llvm::Reloc::ROPI)
357             .Case("rwpi", llvm::Reloc::RWPI)
358             .Case("ropi-rwpi", llvm::Reloc::ROPI_RWPI)
359             .Default(std::nullopt);
360     if (relocModel.has_value())
361       opts.setRelocationModel(*relocModel);
362     else
363       diags.Report(clang::diag::err_drv_invalid_value)
364           << a->getAsString(args) << modelName;
365   }
366 
367   // -pic-level and -pic-is-pie option.
368   if (int picLevel = getLastArgIntValue(
369           args, clang::driver::options::OPT_pic_level, 0, diags)) {
370     if (picLevel > 2)
371       diags.Report(clang::diag::err_drv_invalid_value)
372           << args.getLastArg(clang::driver::options::OPT_pic_level)
373                  ->getAsString(args)
374           << picLevel;
375 
376     opts.PICLevel = picLevel;
377     if (args.hasArg(clang::driver::options::OPT_pic_is_pie))
378       opts.IsPIE = 1;
379   }
380 
381   // This option is compatible with -f[no-]underscoring in gfortran.
382   if (args.hasFlag(clang::driver::options::OPT_fno_underscoring,
383                    clang::driver::options::OPT_funderscoring, false)) {
384     opts.Underscoring = 0;
385   }
386 }
387 
388 /// Parses all target input arguments and populates the target
389 /// options accordingly.
390 ///
391 /// \param [in] opts The target options instance to update
392 /// \param [in] args The list of input arguments (from the compiler invocation)
393 static void parseTargetArgs(TargetOptions &opts, llvm::opt::ArgList &args) {
394   if (const llvm::opt::Arg *a =
395           args.getLastArg(clang::driver::options::OPT_triple))
396     opts.triple = a->getValue();
397 
398   if (const llvm::opt::Arg *a =
399           args.getLastArg(clang::driver::options::OPT_target_cpu))
400     opts.cpu = a->getValue();
401 
402   for (const llvm::opt::Arg *currentArg :
403        args.filtered(clang::driver::options::OPT_target_feature))
404     opts.featuresAsWritten.emplace_back(currentArg->getValue());
405 }
406 
407 // Tweak the frontend configuration based on the frontend action
408 static void setUpFrontendBasedOnAction(FrontendOptions &opts) {
409   if (opts.programAction == DebugDumpParsingLog)
410     opts.instrumentedParse = true;
411 
412   if (opts.programAction == DebugDumpProvenance ||
413       opts.programAction == Fortran::frontend::GetDefinition)
414     opts.needProvenanceRangeToCharBlockMappings = true;
415 }
416 
417 /// Parse the argument specified for the -fconvert=<value> option
418 static std::optional<const char *> parseConvertArg(const char *s) {
419   return llvm::StringSwitch<std::optional<const char *>>(s)
420       .Case("unknown", "UNKNOWN")
421       .Case("native", "NATIVE")
422       .Case("little-endian", "LITTLE_ENDIAN")
423       .Case("big-endian", "BIG_ENDIAN")
424       .Case("swap", "SWAP")
425       .Default(std::nullopt);
426 }
427 
428 static bool parseFrontendArgs(FrontendOptions &opts, llvm::opt::ArgList &args,
429                               clang::DiagnosticsEngine &diags) {
430   unsigned numErrorsBefore = diags.getNumErrors();
431 
432   // By default the frontend driver creates a ParseSyntaxOnly action.
433   opts.programAction = ParseSyntaxOnly;
434 
435   // Treat multiple action options as an invocation error. Note that `clang
436   // -cc1` does accept multiple action options, but will only consider the
437   // rightmost one.
438   if (args.hasMultipleArgs(clang::driver::options::OPT_Action_Group)) {
439     const unsigned diagID = diags.getCustomDiagID(
440         clang::DiagnosticsEngine::Error, "Only one action option is allowed");
441     diags.Report(diagID);
442     return false;
443   }
444 
445   // Identify the action (i.e. opts.ProgramAction)
446   if (const llvm::opt::Arg *a =
447           args.getLastArg(clang::driver::options::OPT_Action_Group)) {
448     switch (a->getOption().getID()) {
449     default: {
450       llvm_unreachable("Invalid option in group!");
451     }
452     case clang::driver::options::OPT_test_io:
453       opts.programAction = InputOutputTest;
454       break;
455     case clang::driver::options::OPT_E:
456       opts.programAction = PrintPreprocessedInput;
457       break;
458     case clang::driver::options::OPT_fsyntax_only:
459       opts.programAction = ParseSyntaxOnly;
460       break;
461     case clang::driver::options::OPT_emit_fir:
462       opts.programAction = EmitFIR;
463       break;
464     case clang::driver::options::OPT_emit_hlfir:
465       opts.programAction = EmitHLFIR;
466       break;
467     case clang::driver::options::OPT_emit_llvm:
468       opts.programAction = EmitLLVM;
469       break;
470     case clang::driver::options::OPT_emit_llvm_bc:
471       opts.programAction = EmitLLVMBitcode;
472       break;
473     case clang::driver::options::OPT_emit_obj:
474       opts.programAction = EmitObj;
475       break;
476     case clang::driver::options::OPT_S:
477       opts.programAction = EmitAssembly;
478       break;
479     case clang::driver::options::OPT_fdebug_unparse:
480       opts.programAction = DebugUnparse;
481       break;
482     case clang::driver::options::OPT_fdebug_unparse_no_sema:
483       opts.programAction = DebugUnparseNoSema;
484       break;
485     case clang::driver::options::OPT_fdebug_unparse_with_symbols:
486       opts.programAction = DebugUnparseWithSymbols;
487       break;
488     case clang::driver::options::OPT_fdebug_dump_symbols:
489       opts.programAction = DebugDumpSymbols;
490       break;
491     case clang::driver::options::OPT_fdebug_dump_parse_tree:
492       opts.programAction = DebugDumpParseTree;
493       break;
494     case clang::driver::options::OPT_fdebug_dump_pft:
495       opts.programAction = DebugDumpPFT;
496       break;
497     case clang::driver::options::OPT_fdebug_dump_all:
498       opts.programAction = DebugDumpAll;
499       break;
500     case clang::driver::options::OPT_fdebug_dump_parse_tree_no_sema:
501       opts.programAction = DebugDumpParseTreeNoSema;
502       break;
503     case clang::driver::options::OPT_fdebug_dump_provenance:
504       opts.programAction = DebugDumpProvenance;
505       break;
506     case clang::driver::options::OPT_fdebug_dump_parsing_log:
507       opts.programAction = DebugDumpParsingLog;
508       break;
509     case clang::driver::options::OPT_fdebug_measure_parse_tree:
510       opts.programAction = DebugMeasureParseTree;
511       break;
512     case clang::driver::options::OPT_fdebug_pre_fir_tree:
513       opts.programAction = DebugPreFIRTree;
514       break;
515     case clang::driver::options::OPT_fget_symbols_sources:
516       opts.programAction = GetSymbolsSources;
517       break;
518     case clang::driver::options::OPT_fget_definition:
519       opts.programAction = GetDefinition;
520       break;
521     case clang::driver::options::OPT_init_only:
522       opts.programAction = InitOnly;
523       break;
524 
525       // TODO:
526       // case clang::driver::options::OPT_emit_llvm:
527       // case clang::driver::options::OPT_emit_llvm_only:
528       // case clang::driver::options::OPT_emit_codegen_only:
529       // case clang::driver::options::OPT_emit_module:
530       // (...)
531     }
532 
533     // Parse the values provided with `-fget-definition` (there should be 3
534     // integers)
535     if (llvm::opt::OptSpecifier(a->getOption().getID()) ==
536         clang::driver::options::OPT_fget_definition) {
537       unsigned optVals[3] = {0, 0, 0};
538 
539       for (unsigned i = 0; i < 3; i++) {
540         llvm::StringRef val = a->getValue(i);
541 
542         if (val.getAsInteger(10, optVals[i])) {
543           // A non-integer was encountered - that's an error.
544           diags.Report(clang::diag::err_drv_invalid_value)
545               << a->getOption().getName() << val;
546           break;
547         }
548       }
549       opts.getDefVals.line = optVals[0];
550       opts.getDefVals.startColumn = optVals[1];
551       opts.getDefVals.endColumn = optVals[2];
552     }
553   }
554 
555   // Parsing -load <dsopath> option and storing shared object path
556   if (llvm::opt::Arg *a = args.getLastArg(clang::driver::options::OPT_load)) {
557     opts.plugins.push_back(a->getValue());
558   }
559 
560   // Parsing -plugin <name> option and storing plugin name and setting action
561   if (const llvm::opt::Arg *a =
562           args.getLastArg(clang::driver::options::OPT_plugin)) {
563     opts.programAction = PluginAction;
564     opts.actionName = a->getValue();
565   }
566 
567   opts.outputFile = args.getLastArgValue(clang::driver::options::OPT_o);
568   opts.showHelp = args.hasArg(clang::driver::options::OPT_help);
569   opts.showVersion = args.hasArg(clang::driver::options::OPT_version);
570 
571   // Get the input kind (from the value passed via `-x`)
572   InputKind dashX(Language::Unknown);
573   if (const llvm::opt::Arg *a =
574           args.getLastArg(clang::driver::options::OPT_x)) {
575     llvm::StringRef xValue = a->getValue();
576     // Principal languages.
577     dashX = llvm::StringSwitch<InputKind>(xValue)
578                 // Flang does not differentiate between pre-processed and not
579                 // pre-processed inputs.
580                 .Case("f95", Language::Fortran)
581                 .Case("f95-cpp-input", Language::Fortran)
582                 .Default(Language::Unknown);
583 
584     // Flang's intermediate representations.
585     if (dashX.isUnknown())
586       dashX = llvm::StringSwitch<InputKind>(xValue)
587                   .Case("ir", Language::LLVM_IR)
588                   .Case("fir", Language::MLIR)
589                   .Case("mlir", Language::MLIR)
590                   .Default(Language::Unknown);
591 
592     if (dashX.isUnknown())
593       diags.Report(clang::diag::err_drv_invalid_value)
594           << a->getAsString(args) << a->getValue();
595   }
596 
597   // Collect the input files and save them in our instance of FrontendOptions.
598   std::vector<std::string> inputs =
599       args.getAllArgValues(clang::driver::options::OPT_INPUT);
600   opts.inputs.clear();
601   if (inputs.empty())
602     // '-' is the default input if none is given.
603     inputs.push_back("-");
604   for (unsigned i = 0, e = inputs.size(); i != e; ++i) {
605     InputKind ik = dashX;
606     if (ik.isUnknown()) {
607       ik = FrontendOptions::getInputKindForExtension(
608           llvm::StringRef(inputs[i]).rsplit('.').second);
609       if (ik.isUnknown())
610         ik = Language::Unknown;
611       if (i == 0)
612         dashX = ik;
613     }
614 
615     opts.inputs.emplace_back(std::move(inputs[i]), ik);
616   }
617 
618   // Set fortranForm based on options -ffree-form and -ffixed-form.
619   if (const auto *arg =
620           args.getLastArg(clang::driver::options::OPT_ffixed_form,
621                           clang::driver::options::OPT_ffree_form)) {
622     opts.fortranForm =
623         arg->getOption().matches(clang::driver::options::OPT_ffixed_form)
624             ? FortranForm::FixedForm
625             : FortranForm::FreeForm;
626   }
627 
628   // Set fixedFormColumns based on -ffixed-line-length=<value>
629   if (const auto *arg =
630           args.getLastArg(clang::driver::options::OPT_ffixed_line_length_EQ)) {
631     llvm::StringRef argValue = llvm::StringRef(arg->getValue());
632     std::int64_t columns = -1;
633     if (argValue == "none") {
634       columns = 0;
635     } else if (argValue.getAsInteger(/*Radix=*/10, columns)) {
636       columns = -1;
637     }
638     if (columns < 0) {
639       diags.Report(clang::diag::err_drv_negative_columns)
640           << arg->getOption().getName() << arg->getValue();
641     } else if (columns == 0) {
642       opts.fixedFormColumns = 1000000;
643     } else if (columns < 7) {
644       diags.Report(clang::diag::err_drv_small_columns)
645           << arg->getOption().getName() << arg->getValue() << "7";
646     } else {
647       opts.fixedFormColumns = columns;
648     }
649   }
650 
651   // Set conversion based on -fconvert=<value>
652   if (const auto *arg =
653           args.getLastArg(clang::driver::options::OPT_fconvert_EQ)) {
654     const char *argValue = arg->getValue();
655     if (auto convert = parseConvertArg(argValue))
656       opts.envDefaults.push_back({"FORT_CONVERT", *convert});
657     else
658       diags.Report(clang::diag::err_drv_invalid_value)
659           << arg->getAsString(args) << argValue;
660   }
661 
662   // -f{no-}implicit-none
663   opts.features.Enable(
664       Fortran::common::LanguageFeature::ImplicitNoneTypeAlways,
665       args.hasFlag(clang::driver::options::OPT_fimplicit_none,
666                    clang::driver::options::OPT_fno_implicit_none, false));
667 
668   // -f{no-}backslash
669   opts.features.Enable(Fortran::common::LanguageFeature::BackslashEscapes,
670                        args.hasFlag(clang::driver::options::OPT_fbackslash,
671                                     clang::driver::options::OPT_fno_backslash,
672                                     false));
673 
674   // -f{no-}logical-abbreviations
675   opts.features.Enable(
676       Fortran::common::LanguageFeature::LogicalAbbreviations,
677       args.hasFlag(clang::driver::options::OPT_flogical_abbreviations,
678                    clang::driver::options::OPT_fno_logical_abbreviations,
679                    false));
680 
681   // -f{no-}xor-operator
682   opts.features.Enable(
683       Fortran::common::LanguageFeature::XOROperator,
684       args.hasFlag(clang::driver::options::OPT_fxor_operator,
685                    clang::driver::options::OPT_fno_xor_operator, false));
686 
687   // -fno-automatic
688   if (args.hasArg(clang::driver::options::OPT_fno_automatic)) {
689     opts.features.Enable(Fortran::common::LanguageFeature::DefaultSave);
690   }
691 
692   if (args.hasArg(
693           clang::driver::options::OPT_falternative_parameter_statement)) {
694     opts.features.Enable(Fortran::common::LanguageFeature::OldStyleParameter);
695   }
696   if (const llvm::opt::Arg *arg =
697           args.getLastArg(clang::driver::options::OPT_finput_charset_EQ)) {
698     llvm::StringRef argValue = arg->getValue();
699     if (argValue == "utf-8") {
700       opts.encoding = Fortran::parser::Encoding::UTF_8;
701     } else if (argValue == "latin-1") {
702       opts.encoding = Fortran::parser::Encoding::LATIN_1;
703     } else {
704       diags.Report(clang::diag::err_drv_invalid_value)
705           << arg->getAsString(args) << argValue;
706     }
707   }
708 
709   setUpFrontendBasedOnAction(opts);
710   opts.dashX = dashX;
711 
712   return diags.getNumErrors() == numErrorsBefore;
713 }
714 
715 // Generate the path to look for intrinsic modules
716 static std::string getIntrinsicDir(const char *argv) {
717   // TODO: Find a system independent API
718   llvm::SmallString<128> driverPath;
719   driverPath.assign(llvm::sys::fs::getMainExecutable(argv, nullptr));
720   llvm::sys::path::remove_filename(driverPath);
721   driverPath.append("/../include/flang/");
722   return std::string(driverPath);
723 }
724 
725 // Generate the path to look for OpenMP headers
726 static std::string getOpenMPHeadersDir(const char *argv) {
727   llvm::SmallString<128> includePath;
728   includePath.assign(llvm::sys::fs::getMainExecutable(argv, nullptr));
729   llvm::sys::path::remove_filename(includePath);
730   includePath.append("/../include/flang/OpenMP/");
731   return std::string(includePath);
732 }
733 
734 /// Parses all preprocessor input arguments and populates the preprocessor
735 /// options accordingly.
736 ///
737 /// \param [in] opts The preprocessor options instance
738 /// \param [out] args The list of input arguments
739 static void parsePreprocessorArgs(Fortran::frontend::PreprocessorOptions &opts,
740                                   llvm::opt::ArgList &args) {
741   // Add macros from the command line.
742   for (const auto *currentArg : args.filtered(clang::driver::options::OPT_D,
743                                               clang::driver::options::OPT_U)) {
744     if (currentArg->getOption().matches(clang::driver::options::OPT_D)) {
745       opts.addMacroDef(currentArg->getValue());
746     } else {
747       opts.addMacroUndef(currentArg->getValue());
748     }
749   }
750 
751   // Add the ordered list of -I's.
752   for (const auto *currentArg : args.filtered(clang::driver::options::OPT_I))
753     opts.searchDirectoriesFromDashI.emplace_back(currentArg->getValue());
754 
755   // Prepend the ordered list of -intrinsic-modules-path
756   // to the default location to search.
757   for (const auto *currentArg :
758        args.filtered(clang::driver::options::OPT_fintrinsic_modules_path))
759     opts.searchDirectoriesFromIntrModPath.emplace_back(currentArg->getValue());
760 
761   // -cpp/-nocpp
762   if (const auto *currentArg = args.getLastArg(
763           clang::driver::options::OPT_cpp, clang::driver::options::OPT_nocpp))
764     opts.macrosFlag =
765         (currentArg->getOption().matches(clang::driver::options::OPT_cpp))
766             ? PPMacrosFlag::Include
767             : PPMacrosFlag::Exclude;
768 
769   opts.noReformat = args.hasArg(clang::driver::options::OPT_fno_reformat);
770   opts.noLineDirectives = args.hasArg(clang::driver::options::OPT_P);
771 }
772 
773 /// Parses all semantic related arguments and populates the variables
774 /// options accordingly. Returns false if new errors are generated.
775 static bool parseSemaArgs(CompilerInvocation &res, llvm::opt::ArgList &args,
776                           clang::DiagnosticsEngine &diags) {
777   unsigned numErrorsBefore = diags.getNumErrors();
778 
779   // -J/module-dir option
780   auto moduleDirList =
781       args.getAllArgValues(clang::driver::options::OPT_module_dir);
782   // User can only specify -J/-module-dir once
783   // https://gcc.gnu.org/onlinedocs/gfortran/Directory-Options.html
784   if (moduleDirList.size() > 1) {
785     const unsigned diagID =
786         diags.getCustomDiagID(clang::DiagnosticsEngine::Error,
787                               "Only one '-module-dir/-J' option allowed");
788     diags.Report(diagID);
789   }
790   if (moduleDirList.size() == 1)
791     res.setModuleDir(moduleDirList[0]);
792 
793   // -fdebug-module-writer option
794   if (args.hasArg(clang::driver::options::OPT_fdebug_module_writer)) {
795     res.setDebugModuleDir(true);
796   }
797 
798   // -module-suffix
799   if (const auto *moduleSuffix =
800           args.getLastArg(clang::driver::options::OPT_module_suffix)) {
801     res.setModuleFileSuffix(moduleSuffix->getValue());
802   }
803 
804   // -f{no-}analyzed-objects-for-unparse
805   res.setUseAnalyzedObjectsForUnparse(args.hasFlag(
806       clang::driver::options::OPT_fanalyzed_objects_for_unparse,
807       clang::driver::options::OPT_fno_analyzed_objects_for_unparse, true));
808 
809   return diags.getNumErrors() == numErrorsBefore;
810 }
811 
812 /// Parses all diagnostics related arguments and populates the variables
813 /// options accordingly. Returns false if new errors are generated.
814 static bool parseDiagArgs(CompilerInvocation &res, llvm::opt::ArgList &args,
815                           clang::DiagnosticsEngine &diags) {
816   unsigned numErrorsBefore = diags.getNumErrors();
817 
818   // -Werror option
819   // TODO: Currently throws a Diagnostic for anything other than -W<error>,
820   // this has to change when other -W<opt>'s are supported.
821   if (args.hasArg(clang::driver::options::OPT_W_Joined)) {
822     const auto &wArgs =
823         args.getAllArgValues(clang::driver::options::OPT_W_Joined);
824     for (const auto &wArg : wArgs) {
825       if (wArg == "error") {
826         res.setWarnAsErr(true);
827       } else {
828         const unsigned diagID =
829             diags.getCustomDiagID(clang::DiagnosticsEngine::Error,
830                                   "Only `-Werror` is supported currently.");
831         diags.Report(diagID);
832       }
833     }
834   }
835 
836   // Default to off for `flang-new -fc1`.
837   res.getFrontendOpts().showColors =
838       parseShowColorsArgs(args, /*defaultDiagColor=*/false);
839 
840   // Honor color diagnostics.
841   res.getDiagnosticOpts().ShowColors = res.getFrontendOpts().showColors;
842 
843   return diags.getNumErrors() == numErrorsBefore;
844 }
845 
846 /// Parses all Dialect related arguments and populates the variables
847 /// options accordingly. Returns false if new errors are generated.
848 static bool parseDialectArgs(CompilerInvocation &res, llvm::opt::ArgList &args,
849                              clang::DiagnosticsEngine &diags) {
850   unsigned numErrorsBefore = diags.getNumErrors();
851 
852   // -fdefault* family
853   if (args.hasArg(clang::driver::options::OPT_fdefault_real_8)) {
854     res.getDefaultKinds().set_defaultRealKind(8);
855     res.getDefaultKinds().set_doublePrecisionKind(16);
856   }
857   if (args.hasArg(clang::driver::options::OPT_fdefault_integer_8)) {
858     res.getDefaultKinds().set_defaultIntegerKind(8);
859     res.getDefaultKinds().set_subscriptIntegerKind(8);
860     res.getDefaultKinds().set_sizeIntegerKind(8);
861     res.getDefaultKinds().set_defaultLogicalKind(8);
862   }
863   if (args.hasArg(clang::driver::options::OPT_fdefault_double_8)) {
864     if (!args.hasArg(clang::driver::options::OPT_fdefault_real_8)) {
865       // -fdefault-double-8 has to be used with -fdefault-real-8
866       // to be compatible with gfortran
867       const unsigned diagID = diags.getCustomDiagID(
868           clang::DiagnosticsEngine::Error,
869           "Use of `-fdefault-double-8` requires `-fdefault-real-8`");
870       diags.Report(diagID);
871     }
872     // https://gcc.gnu.org/onlinedocs/gfortran/Fortran-Dialect-Options.html
873     res.getDefaultKinds().set_doublePrecisionKind(8);
874   }
875   if (args.hasArg(clang::driver::options::OPT_flarge_sizes))
876     res.getDefaultKinds().set_sizeIntegerKind(8);
877 
878   // -fopenmp and -fopenacc
879   if (args.hasArg(clang::driver::options::OPT_fopenacc)) {
880     res.getFrontendOpts().features.Enable(
881         Fortran::common::LanguageFeature::OpenACC);
882   }
883   if (args.hasArg(clang::driver::options::OPT_fopenmp)) {
884     // By default OpenMP is set to 1.1 version
885     res.getLangOpts().OpenMPVersion = 11;
886     res.getFrontendOpts().features.Enable(
887         Fortran::common::LanguageFeature::OpenMP);
888     if (int Version = getLastArgIntValue(
889             args, clang::driver::options::OPT_fopenmp_version_EQ,
890             res.getLangOpts().OpenMPVersion, diags)) {
891       res.getLangOpts().OpenMPVersion = Version;
892     }
893     if (args.hasArg(clang::driver::options::OPT_fopenmp_is_target_device)) {
894       res.getLangOpts().OpenMPIsTargetDevice = 1;
895 
896       // Get OpenMP host file path if any and report if a non existent file is
897       // found
898       if (auto *arg = args.getLastArg(
899               clang::driver::options::OPT_fopenmp_host_ir_file_path)) {
900         res.getLangOpts().OMPHostIRFile = arg->getValue();
901         if (!llvm::sys::fs::exists(res.getLangOpts().OMPHostIRFile))
902           diags.Report(clang::diag::err_drv_omp_host_ir_file_not_found)
903               << res.getLangOpts().OMPHostIRFile;
904       }
905 
906       if (args.hasFlag(
907               clang::driver::options::OPT_fopenmp_assume_teams_oversubscription,
908               clang::driver::options::
909                   OPT_fno_openmp_assume_teams_oversubscription,
910               /*Default=*/false))
911         res.getLangOpts().OpenMPTeamSubscription = true;
912 
913       if (args.hasArg(
914               clang::driver::options::OPT_fopenmp_assume_no_thread_state))
915         res.getLangOpts().OpenMPNoThreadState = 1;
916 
917       if (args.hasArg(
918               clang::driver::options::OPT_fopenmp_assume_no_nested_parallelism))
919         res.getLangOpts().OpenMPNoNestedParallelism = 1;
920 
921       if (args.hasFlag(clang::driver::options::
922                            OPT_fopenmp_assume_threads_oversubscription,
923                        clang::driver::options::
924                            OPT_fno_openmp_assume_threads_oversubscription,
925                        /*Default=*/false))
926         res.getLangOpts().OpenMPThreadSubscription = true;
927 
928       if ((args.hasArg(clang::driver::options::OPT_fopenmp_target_debug) ||
929            args.hasArg(clang::driver::options::OPT_fopenmp_target_debug_EQ))) {
930         res.getLangOpts().OpenMPTargetDebug = getLastArgIntValue(
931             args, clang::driver::options::OPT_fopenmp_target_debug_EQ,
932             res.getLangOpts().OpenMPTargetDebug, diags);
933 
934         if (!res.getLangOpts().OpenMPTargetDebug &&
935             args.hasArg(clang::driver::options::OPT_fopenmp_target_debug))
936           res.getLangOpts().OpenMPTargetDebug = 1;
937       }
938       if (args.hasArg(clang::driver::options::OPT_nogpulib))
939         res.getLangOpts().NoGPULib = 1;
940     }
941 
942     switch (llvm::Triple(res.getTargetOpts().triple).getArch()) {
943     case llvm::Triple::nvptx:
944     case llvm::Triple::nvptx64:
945     case llvm::Triple::amdgcn:
946       if (!res.getLangOpts().OpenMPIsTargetDevice) {
947         const unsigned diagID = diags.getCustomDiagID(
948             clang::DiagnosticsEngine::Error,
949             "OpenMP AMDGPU/NVPTX is only prepared to deal with device code.");
950         diags.Report(diagID);
951       }
952       res.getLangOpts().OpenMPIsGPU = 1;
953       break;
954     default:
955       res.getLangOpts().OpenMPIsGPU = 0;
956       break;
957     }
958   }
959 
960   // -pedantic
961   if (args.hasArg(clang::driver::options::OPT_pedantic)) {
962     res.setEnableConformanceChecks();
963     res.setEnableUsageChecks();
964   }
965   // -std=f2018
966   // TODO: Set proper options when more fortran standards
967   // are supported.
968   if (args.hasArg(clang::driver::options::OPT_std_EQ)) {
969     auto standard = args.getLastArgValue(clang::driver::options::OPT_std_EQ);
970     // We only allow f2018 as the given standard
971     if (standard.equals("f2018")) {
972       res.setEnableConformanceChecks();
973     } else {
974       const unsigned diagID =
975           diags.getCustomDiagID(clang::DiagnosticsEngine::Error,
976                                 "Only -std=f2018 is allowed currently.");
977       diags.Report(diagID);
978     }
979   }
980   return diags.getNumErrors() == numErrorsBefore;
981 }
982 
983 /// Parses all floating point related arguments and populates the
984 /// CompilerInvocation accordingly.
985 /// Returns false if new errors are generated.
986 ///
987 /// \param [out] invoc Stores the processed arguments
988 /// \param [in] args The compiler invocation arguments to parse
989 /// \param [out] diags DiagnosticsEngine to report erros with
990 static bool parseFloatingPointArgs(CompilerInvocation &invoc,
991                                    llvm::opt::ArgList &args,
992                                    clang::DiagnosticsEngine &diags) {
993   LangOptions &opts = invoc.getLangOpts();
994 
995   if (const llvm::opt::Arg *a =
996           args.getLastArg(clang::driver::options::OPT_ffp_contract)) {
997     const llvm::StringRef val = a->getValue();
998     enum LangOptions::FPModeKind fpContractMode;
999 
1000     if (val == "off")
1001       fpContractMode = LangOptions::FPM_Off;
1002     else if (val == "fast")
1003       fpContractMode = LangOptions::FPM_Fast;
1004     else {
1005       diags.Report(clang::diag::err_drv_unsupported_option_argument)
1006           << a->getSpelling() << val;
1007       return false;
1008     }
1009 
1010     opts.setFPContractMode(fpContractMode);
1011   }
1012 
1013   if (args.getLastArg(clang::driver::options::OPT_menable_no_infinities)) {
1014     opts.NoHonorInfs = true;
1015   }
1016 
1017   if (args.getLastArg(clang::driver::options::OPT_menable_no_nans)) {
1018     opts.NoHonorNaNs = true;
1019   }
1020 
1021   if (args.getLastArg(clang::driver::options::OPT_fapprox_func)) {
1022     opts.ApproxFunc = true;
1023   }
1024 
1025   if (args.getLastArg(clang::driver::options::OPT_fno_signed_zeros)) {
1026     opts.NoSignedZeros = true;
1027   }
1028 
1029   if (args.getLastArg(clang::driver::options::OPT_mreassociate)) {
1030     opts.AssociativeMath = true;
1031   }
1032 
1033   if (args.getLastArg(clang::driver::options::OPT_freciprocal_math)) {
1034     opts.ReciprocalMath = true;
1035   }
1036 
1037   if (args.getLastArg(clang::driver::options::OPT_ffast_math)) {
1038     opts.NoHonorInfs = true;
1039     opts.NoHonorNaNs = true;
1040     opts.AssociativeMath = true;
1041     opts.ReciprocalMath = true;
1042     opts.ApproxFunc = true;
1043     opts.NoSignedZeros = true;
1044     opts.setFPContractMode(LangOptions::FPM_Fast);
1045   }
1046 
1047   return true;
1048 }
1049 
1050 /// Parses vscale range options and populates the CompilerInvocation
1051 /// accordingly.
1052 /// Returns false if new errors are generated.
1053 ///
1054 /// \param [out] invoc Stores the processed arguments
1055 /// \param [in] args The compiler invocation arguments to parse
1056 /// \param [out] diags DiagnosticsEngine to report erros with
1057 static bool parseVScaleArgs(CompilerInvocation &invoc, llvm::opt::ArgList &args,
1058                             clang::DiagnosticsEngine &diags) {
1059   const auto *vscaleMin =
1060       args.getLastArg(clang::driver::options::OPT_mvscale_min_EQ);
1061   const auto *vscaleMax =
1062       args.getLastArg(clang::driver::options::OPT_mvscale_max_EQ);
1063 
1064   if (!vscaleMin && !vscaleMax)
1065     return true;
1066 
1067   llvm::Triple triple = llvm::Triple(invoc.getTargetOpts().triple);
1068   if (!triple.isAArch64() && !triple.isRISCV()) {
1069     const unsigned diagID =
1070         diags.getCustomDiagID(clang::DiagnosticsEngine::Error,
1071                               "`-mvscale-max` and `-mvscale-min` are not "
1072                               "supported for this architecture: %0");
1073     diags.Report(diagID) << triple.getArchName();
1074     return false;
1075   }
1076 
1077   LangOptions &opts = invoc.getLangOpts();
1078   if (vscaleMin) {
1079     llvm::StringRef argValue = llvm::StringRef(vscaleMin->getValue());
1080     unsigned vscaleMinVal;
1081     if (argValue.getAsInteger(/*Radix=*/10, vscaleMinVal)) {
1082       diags.Report(clang::diag::err_drv_unsupported_option_argument)
1083           << vscaleMax->getSpelling() << argValue;
1084       return false;
1085     }
1086     opts.VScaleMin = vscaleMinVal;
1087   }
1088 
1089   if (vscaleMax) {
1090     llvm::StringRef argValue = llvm::StringRef(vscaleMax->getValue());
1091     unsigned vscaleMaxVal;
1092     if (argValue.getAsInteger(/*Radix=w*/ 10, vscaleMaxVal)) {
1093       diags.Report(clang::diag::err_drv_unsupported_option_argument)
1094           << vscaleMax->getSpelling() << argValue;
1095       return false;
1096     }
1097     opts.VScaleMax = vscaleMaxVal;
1098   }
1099   return true;
1100 }
1101 
1102 static bool parseLinkerOptionsArgs(CompilerInvocation &invoc,
1103                                    llvm::opt::ArgList &args,
1104                                    clang::DiagnosticsEngine &diags) {
1105   llvm::Triple triple = llvm::Triple(invoc.getTargetOpts().triple);
1106 
1107   // TODO: support --dependent-lib on other platforms when MLIR supports
1108   //       !llvm.dependent.lib
1109   if (args.hasArg(clang::driver::options::OPT_dependent_lib) &&
1110       !triple.isOSWindows()) {
1111     const unsigned diagID =
1112         diags.getCustomDiagID(clang::DiagnosticsEngine::Error,
1113                               "--dependent-lib is only supported on Windows");
1114     diags.Report(diagID);
1115     return false;
1116   }
1117 
1118   invoc.getCodeGenOpts().DependentLibs =
1119       args.getAllArgValues(clang::driver::options::OPT_dependent_lib);
1120   return true;
1121 }
1122 
1123 bool CompilerInvocation::createFromArgs(
1124     CompilerInvocation &invoc, llvm::ArrayRef<const char *> commandLineArgs,
1125     clang::DiagnosticsEngine &diags, const char *argv0) {
1126 
1127   bool success = true;
1128 
1129   // Set the default triple for this CompilerInvocation. This might be
1130   // overridden by users with `-triple` (see the call to `ParseTargetArgs`
1131   // below).
1132   // NOTE: Like in Clang, it would be nice to use option marshalling
1133   // for this so that the entire logic for setting-up the triple is in one
1134   // place.
1135   invoc.getTargetOpts().triple =
1136       llvm::Triple::normalize(llvm::sys::getDefaultTargetTriple());
1137 
1138   // Parse the arguments
1139   const llvm::opt::OptTable &opts = clang::driver::getDriverOptTable();
1140   llvm::opt::Visibility visibilityMask(clang::driver::options::FC1Option);
1141   unsigned missingArgIndex, missingArgCount;
1142   llvm::opt::InputArgList args = opts.ParseArgs(
1143       commandLineArgs, missingArgIndex, missingArgCount, visibilityMask);
1144 
1145   // Check for missing argument error.
1146   if (missingArgCount) {
1147     diags.Report(clang::diag::err_drv_missing_argument)
1148         << args.getArgString(missingArgIndex) << missingArgCount;
1149     success = false;
1150   }
1151 
1152   // Issue errors on unknown arguments
1153   for (const auto *a : args.filtered(clang::driver::options::OPT_UNKNOWN)) {
1154     auto argString = a->getAsString(args);
1155     std::string nearest;
1156     if (opts.findNearest(argString, nearest, visibilityMask) > 1)
1157       diags.Report(clang::diag::err_drv_unknown_argument) << argString;
1158     else
1159       diags.Report(clang::diag::err_drv_unknown_argument_with_suggestion)
1160           << argString << nearest;
1161     success = false;
1162   }
1163 
1164   // -flang-experimental-hlfir
1165   if (args.hasArg(clang::driver::options::OPT_flang_experimental_hlfir) ||
1166       args.hasArg(clang::driver::options::OPT_emit_hlfir)) {
1167     invoc.loweringOpts.setLowerToHighLevelFIR(true);
1168   }
1169 
1170   // -flang-deprecated-no-hlfir
1171   if (args.hasArg(clang::driver::options::OPT_flang_deprecated_no_hlfir) &&
1172       !args.hasArg(clang::driver::options::OPT_emit_hlfir)) {
1173     if (args.hasArg(clang::driver::options::OPT_flang_experimental_hlfir)) {
1174       const unsigned diagID = diags.getCustomDiagID(
1175           clang::DiagnosticsEngine::Error,
1176           "Options '-flang-experimental-hlfir' and "
1177           "'-flang-deprecated-no-hlfir' cannot be both specified");
1178       diags.Report(diagID);
1179     }
1180     invoc.loweringOpts.setLowerToHighLevelFIR(false);
1181   }
1182 
1183   if (args.hasArg(
1184           clang::driver::options::OPT_flang_experimental_polymorphism)) {
1185     invoc.loweringOpts.setPolymorphicTypeImpl(true);
1186   }
1187 
1188   // -fno-ppc-native-vector-element-order
1189   if (args.hasArg(clang::driver::options::OPT_fno_ppc_native_vec_elem_order)) {
1190     invoc.loweringOpts.setNoPPCNativeVecElemOrder(true);
1191   }
1192 
1193   // Preserve all the remark options requested, i.e. -Rpass, -Rpass-missed or
1194   // -Rpass-analysis. This will be used later when processing and outputting the
1195   // remarks generated by LLVM in ExecuteCompilerInvocation.cpp.
1196   for (auto *a : args.filtered(clang::driver::options::OPT_R_Group)) {
1197     if (a->getOption().matches(clang::driver::options::OPT_R_value_Group))
1198       // This is -Rfoo=, where foo is the name of the diagnostic
1199       // group. Add only the remark option name to the diagnostics. e.g. for
1200       // -Rpass= we will add the string "pass".
1201       invoc.getDiagnosticOpts().Remarks.push_back(
1202           std::string(a->getOption().getName().drop_front(1).rtrim("=-")));
1203     else
1204       // If no regex was provided, add the provided value, e.g. for -Rpass add
1205       // the string "pass".
1206       invoc.getDiagnosticOpts().Remarks.push_back(a->getValue());
1207   }
1208 
1209   success &= parseFrontendArgs(invoc.getFrontendOpts(), args, diags);
1210   parseTargetArgs(invoc.getTargetOpts(), args);
1211   parsePreprocessorArgs(invoc.getPreprocessorOpts(), args);
1212   parseCodeGenArgs(invoc.getCodeGenOpts(), args, diags);
1213   success &= parseDebugArgs(invoc.getCodeGenOpts(), args, diags);
1214   success &= parseVectorLibArg(invoc.getCodeGenOpts(), args, diags);
1215   success &= parseSemaArgs(invoc, args, diags);
1216   success &= parseDialectArgs(invoc, args, diags);
1217   success &= parseDiagArgs(invoc, args, diags);
1218 
1219   // Collect LLVM (-mllvm) and MLIR (-mmlir) options.
1220   // NOTE: Try to avoid adding any options directly to `llvmArgs` or
1221   // `mlirArgs`. Instead, you can use
1222   //    * `-mllvm <your-llvm-option>`, or
1223   //    * `-mmlir <your-mlir-option>`.
1224   invoc.frontendOpts.llvmArgs =
1225       args.getAllArgValues(clang::driver::options::OPT_mllvm);
1226   invoc.frontendOpts.mlirArgs =
1227       args.getAllArgValues(clang::driver::options::OPT_mmlir);
1228 
1229   success &= parseFloatingPointArgs(invoc, args, diags);
1230 
1231   success &= parseVScaleArgs(invoc, args, diags);
1232 
1233   success &= parseLinkerOptionsArgs(invoc, args, diags);
1234 
1235   // Set the string to be used as the return value of the COMPILER_OPTIONS
1236   // intrinsic of iso_fortran_env. This is either passed in from the parent
1237   // compiler driver invocation with an environment variable, or failing that
1238   // set to the command line arguments of the frontend driver invocation.
1239   invoc.allCompilerInvocOpts = std::string();
1240   llvm::raw_string_ostream os(invoc.allCompilerInvocOpts);
1241   char *compilerOptsEnv = std::getenv("FLANG_COMPILER_OPTIONS_STRING");
1242   if (compilerOptsEnv != nullptr) {
1243     os << compilerOptsEnv;
1244   } else {
1245     os << argv0 << ' ';
1246     for (auto it = commandLineArgs.begin(), e = commandLineArgs.end(); it != e;
1247          ++it) {
1248       os << ' ' << *it;
1249     }
1250   }
1251 
1252   invoc.setArgv0(argv0);
1253 
1254   return success;
1255 }
1256 
1257 void CompilerInvocation::collectMacroDefinitions() {
1258   auto &ppOpts = this->getPreprocessorOpts();
1259 
1260   for (unsigned i = 0, n = ppOpts.macros.size(); i != n; ++i) {
1261     llvm::StringRef macro = ppOpts.macros[i].first;
1262     bool isUndef = ppOpts.macros[i].second;
1263 
1264     std::pair<llvm::StringRef, llvm::StringRef> macroPair = macro.split('=');
1265     llvm::StringRef macroName = macroPair.first;
1266     llvm::StringRef macroBody = macroPair.second;
1267 
1268     // For an #undef'd macro, we only care about the name.
1269     if (isUndef) {
1270       parserOpts.predefinitions.emplace_back(macroName.str(),
1271                                              std::optional<std::string>{});
1272       continue;
1273     }
1274 
1275     // For a #define'd macro, figure out the actual definition.
1276     if (macroName.size() == macro.size())
1277       macroBody = "1";
1278     else {
1279       // Note: GCC drops anything following an end-of-line character.
1280       llvm::StringRef::size_type end = macroBody.find_first_of("\n\r");
1281       macroBody = macroBody.substr(0, end);
1282     }
1283     parserOpts.predefinitions.emplace_back(
1284         macroName, std::optional<std::string>(macroBody.str()));
1285   }
1286 }
1287 
1288 void CompilerInvocation::setDefaultFortranOpts() {
1289   auto &fortranOptions = getFortranOpts();
1290 
1291   std::vector<std::string> searchDirectories{"."s};
1292   fortranOptions.searchDirectories = searchDirectories;
1293 
1294   // Add the location of omp_lib.h to the search directories. Currently this is
1295   // identical to the modules' directory.
1296   fortranOptions.searchDirectories.emplace_back(
1297       getOpenMPHeadersDir(getArgv0()));
1298 
1299   fortranOptions.isFixedForm = false;
1300 }
1301 
1302 // TODO: When expanding this method, consider creating a dedicated API for
1303 // this. Also at some point we will need to differentiate between different
1304 // targets and add dedicated predefines for each.
1305 void CompilerInvocation::setDefaultPredefinitions() {
1306   auto &fortranOptions = getFortranOpts();
1307   const auto &frontendOptions = getFrontendOpts();
1308   // Populate the macro list with version numbers and other predefinitions.
1309   fortranOptions.predefinitions.emplace_back("__flang__", "1");
1310   fortranOptions.predefinitions.emplace_back("__flang_major__",
1311                                              FLANG_VERSION_MAJOR_STRING);
1312   fortranOptions.predefinitions.emplace_back("__flang_minor__",
1313                                              FLANG_VERSION_MINOR_STRING);
1314   fortranOptions.predefinitions.emplace_back("__flang_patchlevel__",
1315                                              FLANG_VERSION_PATCHLEVEL_STRING);
1316 
1317   // Add predefinitions based on extensions enabled
1318   if (frontendOptions.features.IsEnabled(
1319           Fortran::common::LanguageFeature::OpenACC)) {
1320     fortranOptions.predefinitions.emplace_back("_OPENACC", "202211");
1321   }
1322   if (frontendOptions.features.IsEnabled(
1323           Fortran::common::LanguageFeature::OpenMP)) {
1324     Fortran::common::setOpenMPMacro(getLangOpts().OpenMPVersion,
1325                                     fortranOptions.predefinitions);
1326   }
1327   llvm::Triple targetTriple{llvm::Triple(this->targetOpts.triple)};
1328   if (targetTriple.getArch() == llvm::Triple::ArchType::x86_64) {
1329     fortranOptions.predefinitions.emplace_back("__x86_64__", "1");
1330     fortranOptions.predefinitions.emplace_back("__x86_64", "1");
1331   }
1332 }
1333 
1334 void CompilerInvocation::setFortranOpts() {
1335   auto &fortranOptions = getFortranOpts();
1336   const auto &frontendOptions = getFrontendOpts();
1337   const auto &preprocessorOptions = getPreprocessorOpts();
1338   auto &moduleDirJ = getModuleDir();
1339 
1340   if (frontendOptions.fortranForm != FortranForm::Unknown) {
1341     fortranOptions.isFixedForm =
1342         frontendOptions.fortranForm == FortranForm::FixedForm;
1343   }
1344   fortranOptions.fixedFormColumns = frontendOptions.fixedFormColumns;
1345 
1346   fortranOptions.features = frontendOptions.features;
1347   fortranOptions.encoding = frontendOptions.encoding;
1348 
1349   // Adding search directories specified by -I
1350   fortranOptions.searchDirectories.insert(
1351       fortranOptions.searchDirectories.end(),
1352       preprocessorOptions.searchDirectoriesFromDashI.begin(),
1353       preprocessorOptions.searchDirectoriesFromDashI.end());
1354 
1355   // Add the ordered list of -intrinsic-modules-path
1356   fortranOptions.searchDirectories.insert(
1357       fortranOptions.searchDirectories.end(),
1358       preprocessorOptions.searchDirectoriesFromIntrModPath.begin(),
1359       preprocessorOptions.searchDirectoriesFromIntrModPath.end());
1360 
1361   //  Add the default intrinsic module directory
1362   fortranOptions.intrinsicModuleDirectories.emplace_back(
1363       getIntrinsicDir(getArgv0()));
1364 
1365   // Add the directory supplied through -J/-module-dir to the list of search
1366   // directories
1367   if (moduleDirJ != ".")
1368     fortranOptions.searchDirectories.emplace_back(moduleDirJ);
1369 
1370   if (frontendOptions.instrumentedParse)
1371     fortranOptions.instrumentedParse = true;
1372 
1373   if (frontendOptions.showColors)
1374     fortranOptions.showColors = true;
1375 
1376   if (frontendOptions.needProvenanceRangeToCharBlockMappings)
1377     fortranOptions.needProvenanceRangeToCharBlockMappings = true;
1378 
1379   if (getEnableConformanceChecks())
1380     fortranOptions.features.WarnOnAllNonstandard();
1381 
1382   if (getEnableUsageChecks())
1383     fortranOptions.features.WarnOnAllUsage();
1384 }
1385 
1386 std::unique_ptr<Fortran::semantics::SemanticsContext>
1387 CompilerInvocation::getSemanticsCtx(
1388     Fortran::parser::AllCookedSources &allCookedSources,
1389     const llvm::TargetMachine &targetMachine) {
1390   auto &fortranOptions = getFortranOpts();
1391 
1392   auto semanticsContext = std::make_unique<semantics::SemanticsContext>(
1393       getDefaultKinds(), fortranOptions.features, allCookedSources);
1394 
1395   semanticsContext->set_moduleDirectory(getModuleDir())
1396       .set_searchDirectories(fortranOptions.searchDirectories)
1397       .set_intrinsicModuleDirectories(fortranOptions.intrinsicModuleDirectories)
1398       .set_warningsAreErrors(getWarnAsErr())
1399       .set_moduleFileSuffix(getModuleFileSuffix())
1400       .set_underscoring(getCodeGenOpts().Underscoring);
1401 
1402   std::string compilerVersion = Fortran::common::getFlangFullVersion();
1403   Fortran::tools::setUpTargetCharacteristics(
1404       semanticsContext->targetCharacteristics(), targetMachine, compilerVersion,
1405       allCompilerInvocOpts);
1406   return semanticsContext;
1407 }
1408 
1409 /// Set \p loweringOptions controlling lowering behavior based
1410 /// on the \p optimizationLevel.
1411 void CompilerInvocation::setLoweringOptions() {
1412   const CodeGenOptions &codegenOpts = getCodeGenOpts();
1413 
1414   // Lower TRANSPOSE as a runtime call under -O0.
1415   loweringOpts.setOptimizeTranspose(codegenOpts.OptimizationLevel > 0);
1416   loweringOpts.setUnderscoring(codegenOpts.Underscoring);
1417 
1418   const LangOptions &langOptions = getLangOpts();
1419   Fortran::common::MathOptionsBase &mathOpts = loweringOpts.getMathOptions();
1420   // TODO: when LangOptions are finalized, we can represent
1421   //       the math related options using Fortran::commmon::MathOptionsBase,
1422   //       so that we can just copy it into LoweringOptions.
1423   mathOpts
1424       .setFPContractEnabled(langOptions.getFPContractMode() ==
1425                             LangOptions::FPM_Fast)
1426       .setNoHonorInfs(langOptions.NoHonorInfs)
1427       .setNoHonorNaNs(langOptions.NoHonorNaNs)
1428       .setApproxFunc(langOptions.ApproxFunc)
1429       .setNoSignedZeros(langOptions.NoSignedZeros)
1430       .setAssociativeMath(langOptions.AssociativeMath)
1431       .setReciprocalMath(langOptions.ReciprocalMath);
1432 }
1433