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