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