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