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