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