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