xref: /llvm-project/flang/lib/Frontend/CompilerInvocation.cpp (revision ebc2c71d63b69d90aadf07968f821267442f56ef)
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 = llvm::CodeGenOpt::None;
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 llvm::CodeGenOpt::None;
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 void parseCodeGenArgs(Fortran::frontend::CodeGenOptions &opts,
157                              llvm::opt::ArgList &args,
158                              clang::DiagnosticsEngine &diags) {
159   opts.OptimizationLevel = getOptimizationLevel(args, diags);
160 
161   if (args.hasFlag(clang::driver::options::OPT_fdebug_pass_manager,
162                    clang::driver::options::OPT_fno_debug_pass_manager, false))
163     opts.DebugPassManager = 1;
164 
165   if (args.hasFlag(clang::driver::options::OPT_fstack_arrays,
166                    clang::driver::options::OPT_fno_stack_arrays, false)) {
167     opts.StackArrays = 1;
168   }
169   if (args.hasFlag(clang::driver::options::OPT_floop_versioning,
170                    clang::driver::options::OPT_fno_loop_versioning, false)) {
171     opts.LoopVersioning = 1;
172   }
173 
174   for (auto *a : args.filtered(clang::driver::options::OPT_fpass_plugin_EQ))
175     opts.LLVMPassPlugins.push_back(a->getValue());
176 
177   // -fembed-offload-object option
178   for (auto *a :
179        args.filtered(clang::driver::options::OPT_fembed_offload_object_EQ))
180     opts.OffloadObjects.push_back(a->getValue());
181 
182   // -flto=full/thin option.
183   if (const llvm::opt::Arg *a =
184           args.getLastArg(clang::driver::options::OPT_flto_EQ)) {
185     llvm::StringRef s = a->getValue();
186     assert((s == "full" || s == "thin") && "Unknown LTO mode.");
187     if (s == "full")
188       opts.PrepareForFullLTO = true;
189     else
190       opts.PrepareForThinLTO = true;
191   }
192 
193   if (auto *a = args.getLastArg(clang::driver::options::OPT_save_temps_EQ))
194     opts.SaveTempsDir = a->getValue();
195 
196   // -mrelocation-model option.
197   if (const llvm::opt::Arg *a =
198           args.getLastArg(clang::driver::options::OPT_mrelocation_model)) {
199     llvm::StringRef modelName = a->getValue();
200     auto relocModel =
201         llvm::StringSwitch<std::optional<llvm::Reloc::Model>>(modelName)
202             .Case("static", llvm::Reloc::Static)
203             .Case("pic", llvm::Reloc::PIC_)
204             .Case("dynamic-no-pic", llvm::Reloc::DynamicNoPIC)
205             .Case("ropi", llvm::Reloc::ROPI)
206             .Case("rwpi", llvm::Reloc::RWPI)
207             .Case("ropi-rwpi", llvm::Reloc::ROPI_RWPI)
208             .Default(std::nullopt);
209     if (relocModel.has_value())
210       opts.setRelocationModel(*relocModel);
211     else
212       diags.Report(clang::diag::err_drv_invalid_value)
213           << a->getAsString(args) << modelName;
214   }
215 
216   // -pic-level and -pic-is-pie option.
217   if (int picLevel = getLastArgIntValue(
218           args, clang::driver::options::OPT_pic_level, 0, diags)) {
219     if (picLevel > 2)
220       diags.Report(clang::diag::err_drv_invalid_value)
221           << args.getLastArg(clang::driver::options::OPT_pic_level)
222                  ->getAsString(args)
223           << picLevel;
224 
225     opts.PICLevel = picLevel;
226     if (args.hasArg(clang::driver::options::OPT_pic_is_pie))
227       opts.IsPIE = 1;
228   }
229 
230   // This option is compatible with -f[no-]underscoring in gfortran.
231   if (args.hasFlag(clang::driver::options::OPT_fno_underscoring,
232                    clang::driver::options::OPT_funderscoring, false)) {
233     opts.Underscoring = 0;
234   }
235 }
236 
237 /// Parses all target input arguments and populates the target
238 /// options accordingly.
239 ///
240 /// \param [in] opts The target options instance to update
241 /// \param [in] args The list of input arguments (from the compiler invocation)
242 static void parseTargetArgs(TargetOptions &opts, llvm::opt::ArgList &args) {
243   if (const llvm::opt::Arg *a =
244           args.getLastArg(clang::driver::options::OPT_triple))
245     opts.triple = a->getValue();
246 
247   if (const llvm::opt::Arg *a =
248           args.getLastArg(clang::driver::options::OPT_target_cpu))
249     opts.cpu = a->getValue();
250 
251   for (const llvm::opt::Arg *currentArg :
252        args.filtered(clang::driver::options::OPT_target_feature))
253     opts.featuresAsWritten.emplace_back(currentArg->getValue());
254 }
255 
256 // Tweak the frontend configuration based on the frontend action
257 static void setUpFrontendBasedOnAction(FrontendOptions &opts) {
258   if (opts.programAction == DebugDumpParsingLog)
259     opts.instrumentedParse = true;
260 
261   if (opts.programAction == DebugDumpProvenance ||
262       opts.programAction == Fortran::frontend::GetDefinition)
263     opts.needProvenanceRangeToCharBlockMappings = true;
264 }
265 
266 /// Parse the argument specified for the -fconvert=<value> option
267 static std::optional<const char *> parseConvertArg(const char *s) {
268   return llvm::StringSwitch<std::optional<const char *>>(s)
269       .Case("unknown", "UNKNOWN")
270       .Case("native", "NATIVE")
271       .Case("little-endian", "LITTLE_ENDIAN")
272       .Case("big-endian", "BIG_ENDIAN")
273       .Case("swap", "SWAP")
274       .Default(std::nullopt);
275 }
276 
277 static bool parseFrontendArgs(FrontendOptions &opts, llvm::opt::ArgList &args,
278                               clang::DiagnosticsEngine &diags) {
279   unsigned numErrorsBefore = diags.getNumErrors();
280 
281   // By default the frontend driver creates a ParseSyntaxOnly action.
282   opts.programAction = ParseSyntaxOnly;
283 
284   // Treat multiple action options as an invocation error. Note that `clang
285   // -cc1` does accept multiple action options, but will only consider the
286   // rightmost one.
287   if (args.hasMultipleArgs(clang::driver::options::OPT_Action_Group)) {
288     const unsigned diagID = diags.getCustomDiagID(
289         clang::DiagnosticsEngine::Error, "Only one action option is allowed");
290     diags.Report(diagID);
291     return false;
292   }
293 
294   // Identify the action (i.e. opts.ProgramAction)
295   if (const llvm::opt::Arg *a =
296           args.getLastArg(clang::driver::options::OPT_Action_Group)) {
297     switch (a->getOption().getID()) {
298     default: {
299       llvm_unreachable("Invalid option in group!");
300     }
301     case clang::driver::options::OPT_test_io:
302       opts.programAction = InputOutputTest;
303       break;
304     case clang::driver::options::OPT_E:
305       opts.programAction = PrintPreprocessedInput;
306       break;
307     case clang::driver::options::OPT_fsyntax_only:
308       opts.programAction = ParseSyntaxOnly;
309       break;
310     case clang::driver::options::OPT_emit_fir:
311       opts.programAction = EmitFIR;
312       break;
313     case clang::driver::options::OPT_emit_hlfir:
314       opts.programAction = EmitHLFIR;
315       break;
316     case clang::driver::options::OPT_emit_llvm:
317       opts.programAction = EmitLLVM;
318       break;
319     case clang::driver::options::OPT_emit_llvm_bc:
320       opts.programAction = EmitLLVMBitcode;
321       break;
322     case clang::driver::options::OPT_emit_obj:
323       opts.programAction = EmitObj;
324       break;
325     case clang::driver::options::OPT_S:
326       opts.programAction = EmitAssembly;
327       break;
328     case clang::driver::options::OPT_fdebug_unparse:
329       opts.programAction = DebugUnparse;
330       break;
331     case clang::driver::options::OPT_fdebug_unparse_no_sema:
332       opts.programAction = DebugUnparseNoSema;
333       break;
334     case clang::driver::options::OPT_fdebug_unparse_with_symbols:
335       opts.programAction = DebugUnparseWithSymbols;
336       break;
337     case clang::driver::options::OPT_fdebug_dump_symbols:
338       opts.programAction = DebugDumpSymbols;
339       break;
340     case clang::driver::options::OPT_fdebug_dump_parse_tree:
341       opts.programAction = DebugDumpParseTree;
342       break;
343     case clang::driver::options::OPT_fdebug_dump_pft:
344       opts.programAction = DebugDumpPFT;
345       break;
346     case clang::driver::options::OPT_fdebug_dump_all:
347       opts.programAction = DebugDumpAll;
348       break;
349     case clang::driver::options::OPT_fdebug_dump_parse_tree_no_sema:
350       opts.programAction = DebugDumpParseTreeNoSema;
351       break;
352     case clang::driver::options::OPT_fdebug_dump_provenance:
353       opts.programAction = DebugDumpProvenance;
354       break;
355     case clang::driver::options::OPT_fdebug_dump_parsing_log:
356       opts.programAction = DebugDumpParsingLog;
357       break;
358     case clang::driver::options::OPT_fdebug_measure_parse_tree:
359       opts.programAction = DebugMeasureParseTree;
360       break;
361     case clang::driver::options::OPT_fdebug_pre_fir_tree:
362       opts.programAction = DebugPreFIRTree;
363       break;
364     case clang::driver::options::OPT_fget_symbols_sources:
365       opts.programAction = GetSymbolsSources;
366       break;
367     case clang::driver::options::OPT_fget_definition:
368       opts.programAction = GetDefinition;
369       break;
370     case clang::driver::options::OPT_init_only:
371       opts.programAction = InitOnly;
372       break;
373 
374       // TODO:
375       // case clang::driver::options::OPT_emit_llvm:
376       // case clang::driver::options::OPT_emit_llvm_only:
377       // case clang::driver::options::OPT_emit_codegen_only:
378       // case clang::driver::options::OPT_emit_module:
379       // (...)
380     }
381 
382     // Parse the values provided with `-fget-definition` (there should be 3
383     // integers)
384     if (llvm::opt::OptSpecifier(a->getOption().getID()) ==
385         clang::driver::options::OPT_fget_definition) {
386       unsigned optVals[3] = {0, 0, 0};
387 
388       for (unsigned i = 0; i < 3; i++) {
389         llvm::StringRef val = a->getValue(i);
390 
391         if (val.getAsInteger(10, optVals[i])) {
392           // A non-integer was encountered - that's an error.
393           diags.Report(clang::diag::err_drv_invalid_value)
394               << a->getOption().getName() << val;
395           break;
396         }
397       }
398       opts.getDefVals.line = optVals[0];
399       opts.getDefVals.startColumn = optVals[1];
400       opts.getDefVals.endColumn = optVals[2];
401     }
402   }
403 
404   // Parsing -load <dsopath> option and storing shared object path
405   if (llvm::opt::Arg *a = args.getLastArg(clang::driver::options::OPT_load)) {
406     opts.plugins.push_back(a->getValue());
407   }
408 
409   // Parsing -plugin <name> option and storing plugin name and setting action
410   if (const llvm::opt::Arg *a =
411           args.getLastArg(clang::driver::options::OPT_plugin)) {
412     opts.programAction = PluginAction;
413     opts.actionName = a->getValue();
414   }
415 
416   opts.outputFile = args.getLastArgValue(clang::driver::options::OPT_o);
417   opts.showHelp = args.hasArg(clang::driver::options::OPT_help);
418   opts.showVersion = args.hasArg(clang::driver::options::OPT_version);
419 
420   // Get the input kind (from the value passed via `-x`)
421   InputKind dashX(Language::Unknown);
422   if (const llvm::opt::Arg *a =
423           args.getLastArg(clang::driver::options::OPT_x)) {
424     llvm::StringRef xValue = a->getValue();
425     // Principal languages.
426     dashX = llvm::StringSwitch<InputKind>(xValue)
427                 // Flang does not differentiate between pre-processed and not
428                 // pre-processed inputs.
429                 .Case("f95", Language::Fortran)
430                 .Case("f95-cpp-input", Language::Fortran)
431                 .Default(Language::Unknown);
432 
433     // Flang's intermediate representations.
434     if (dashX.isUnknown())
435       dashX = llvm::StringSwitch<InputKind>(xValue)
436                   .Case("ir", Language::LLVM_IR)
437                   .Case("fir", Language::MLIR)
438                   .Case("mlir", Language::MLIR)
439                   .Default(Language::Unknown);
440 
441     if (dashX.isUnknown())
442       diags.Report(clang::diag::err_drv_invalid_value)
443           << a->getAsString(args) << a->getValue();
444   }
445 
446   // Collect the input files and save them in our instance of FrontendOptions.
447   std::vector<std::string> inputs =
448       args.getAllArgValues(clang::driver::options::OPT_INPUT);
449   opts.inputs.clear();
450   if (inputs.empty())
451     // '-' is the default input if none is given.
452     inputs.push_back("-");
453   for (unsigned i = 0, e = inputs.size(); i != e; ++i) {
454     InputKind ik = dashX;
455     if (ik.isUnknown()) {
456       ik = FrontendOptions::getInputKindForExtension(
457           llvm::StringRef(inputs[i]).rsplit('.').second);
458       if (ik.isUnknown())
459         ik = Language::Unknown;
460       if (i == 0)
461         dashX = ik;
462     }
463 
464     opts.inputs.emplace_back(std::move(inputs[i]), ik);
465   }
466 
467   // Set fortranForm based on options -ffree-form and -ffixed-form.
468   if (const auto *arg =
469           args.getLastArg(clang::driver::options::OPT_ffixed_form,
470                           clang::driver::options::OPT_ffree_form)) {
471     opts.fortranForm =
472         arg->getOption().matches(clang::driver::options::OPT_ffixed_form)
473             ? FortranForm::FixedForm
474             : FortranForm::FreeForm;
475   }
476 
477   // Set fixedFormColumns based on -ffixed-line-length=<value>
478   if (const auto *arg =
479           args.getLastArg(clang::driver::options::OPT_ffixed_line_length_EQ)) {
480     llvm::StringRef argValue = llvm::StringRef(arg->getValue());
481     std::int64_t columns = -1;
482     if (argValue == "none") {
483       columns = 0;
484     } else if (argValue.getAsInteger(/*Radix=*/10, columns)) {
485       columns = -1;
486     }
487     if (columns < 0) {
488       diags.Report(clang::diag::err_drv_negative_columns)
489           << arg->getOption().getName() << arg->getValue();
490     } else if (columns == 0) {
491       opts.fixedFormColumns = 1000000;
492     } else if (columns < 7) {
493       diags.Report(clang::diag::err_drv_small_columns)
494           << arg->getOption().getName() << arg->getValue() << "7";
495     } else {
496       opts.fixedFormColumns = columns;
497     }
498   }
499 
500   // Set conversion based on -fconvert=<value>
501   if (const auto *arg =
502           args.getLastArg(clang::driver::options::OPT_fconvert_EQ)) {
503     const char *argValue = arg->getValue();
504     if (auto convert = parseConvertArg(argValue))
505       opts.envDefaults.push_back({"FORT_CONVERT", *convert});
506     else
507       diags.Report(clang::diag::err_drv_invalid_value)
508           << arg->getAsString(args) << argValue;
509   }
510 
511   // -f{no-}implicit-none
512   opts.features.Enable(
513       Fortran::common::LanguageFeature::ImplicitNoneTypeAlways,
514       args.hasFlag(clang::driver::options::OPT_fimplicit_none,
515                    clang::driver::options::OPT_fno_implicit_none, false));
516 
517   // -f{no-}backslash
518   opts.features.Enable(Fortran::common::LanguageFeature::BackslashEscapes,
519                        args.hasFlag(clang::driver::options::OPT_fbackslash,
520                                     clang::driver::options::OPT_fno_backslash,
521                                     false));
522 
523   // -f{no-}logical-abbreviations
524   opts.features.Enable(
525       Fortran::common::LanguageFeature::LogicalAbbreviations,
526       args.hasFlag(clang::driver::options::OPT_flogical_abbreviations,
527                    clang::driver::options::OPT_fno_logical_abbreviations,
528                    false));
529 
530   // -f{no-}xor-operator
531   opts.features.Enable(
532       Fortran::common::LanguageFeature::XOROperator,
533       args.hasFlag(clang::driver::options::OPT_fxor_operator,
534                    clang::driver::options::OPT_fno_xor_operator, false));
535 
536   // -fno-automatic
537   if (args.hasArg(clang::driver::options::OPT_fno_automatic)) {
538     opts.features.Enable(Fortran::common::LanguageFeature::DefaultSave);
539   }
540 
541   if (args.hasArg(
542           clang::driver::options::OPT_falternative_parameter_statement)) {
543     opts.features.Enable(Fortran::common::LanguageFeature::OldStyleParameter);
544   }
545   if (const llvm::opt::Arg *arg =
546           args.getLastArg(clang::driver::options::OPT_finput_charset_EQ)) {
547     llvm::StringRef argValue = arg->getValue();
548     if (argValue == "utf-8") {
549       opts.encoding = Fortran::parser::Encoding::UTF_8;
550     } else if (argValue == "latin-1") {
551       opts.encoding = Fortran::parser::Encoding::LATIN_1;
552     } else {
553       diags.Report(clang::diag::err_drv_invalid_value)
554           << arg->getAsString(args) << argValue;
555     }
556   }
557 
558   setUpFrontendBasedOnAction(opts);
559   opts.dashX = dashX;
560 
561   return diags.getNumErrors() == numErrorsBefore;
562 }
563 
564 // Generate the path to look for intrinsic modules
565 static std::string getIntrinsicDir() {
566   // TODO: Find a system independent API
567   llvm::SmallString<128> driverPath;
568   driverPath.assign(llvm::sys::fs::getMainExecutable(nullptr, nullptr));
569   llvm::sys::path::remove_filename(driverPath);
570   driverPath.append("/../include/flang/");
571   return std::string(driverPath);
572 }
573 
574 // Generate the path to look for OpenMP headers
575 static std::string getOpenMPHeadersDir() {
576   llvm::SmallString<128> includePath;
577   includePath.assign(llvm::sys::fs::getMainExecutable(nullptr, nullptr));
578   llvm::sys::path::remove_filename(includePath);
579   includePath.append("/../include/flang/OpenMP/");
580   return std::string(includePath);
581 }
582 
583 /// Parses all preprocessor input arguments and populates the preprocessor
584 /// options accordingly.
585 ///
586 /// \param [in] opts The preprocessor options instance
587 /// \param [out] args The list of input arguments
588 static void parsePreprocessorArgs(Fortran::frontend::PreprocessorOptions &opts,
589                                   llvm::opt::ArgList &args) {
590   // Add macros from the command line.
591   for (const auto *currentArg : args.filtered(clang::driver::options::OPT_D,
592                                               clang::driver::options::OPT_U)) {
593     if (currentArg->getOption().matches(clang::driver::options::OPT_D)) {
594       opts.addMacroDef(currentArg->getValue());
595     } else {
596       opts.addMacroUndef(currentArg->getValue());
597     }
598   }
599 
600   // Add the ordered list of -I's.
601   for (const auto *currentArg : args.filtered(clang::driver::options::OPT_I))
602     opts.searchDirectoriesFromDashI.emplace_back(currentArg->getValue());
603 
604   // Prepend the ordered list of -intrinsic-modules-path
605   // to the default location to search.
606   for (const auto *currentArg :
607        args.filtered(clang::driver::options::OPT_fintrinsic_modules_path))
608     opts.searchDirectoriesFromIntrModPath.emplace_back(currentArg->getValue());
609 
610   // -cpp/-nocpp
611   if (const auto *currentArg = args.getLastArg(
612           clang::driver::options::OPT_cpp, clang::driver::options::OPT_nocpp))
613     opts.macrosFlag =
614         (currentArg->getOption().matches(clang::driver::options::OPT_cpp))
615             ? PPMacrosFlag::Include
616             : PPMacrosFlag::Exclude;
617 
618   opts.noReformat = args.hasArg(clang::driver::options::OPT_fno_reformat);
619   opts.noLineDirectives = args.hasArg(clang::driver::options::OPT_P);
620 }
621 
622 /// Parses all semantic related arguments and populates the variables
623 /// options accordingly. Returns false if new errors are generated.
624 static bool parseSemaArgs(CompilerInvocation &res, llvm::opt::ArgList &args,
625                           clang::DiagnosticsEngine &diags) {
626   unsigned numErrorsBefore = diags.getNumErrors();
627 
628   // -J/module-dir option
629   auto moduleDirList =
630       args.getAllArgValues(clang::driver::options::OPT_module_dir);
631   // User can only specify -J/-module-dir once
632   // https://gcc.gnu.org/onlinedocs/gfortran/Directory-Options.html
633   if (moduleDirList.size() > 1) {
634     const unsigned diagID =
635         diags.getCustomDiagID(clang::DiagnosticsEngine::Error,
636                               "Only one '-module-dir/-J' option allowed");
637     diags.Report(diagID);
638   }
639   if (moduleDirList.size() == 1)
640     res.setModuleDir(moduleDirList[0]);
641 
642   // -fdebug-module-writer option
643   if (args.hasArg(clang::driver::options::OPT_fdebug_module_writer)) {
644     res.setDebugModuleDir(true);
645   }
646 
647   // -module-suffix
648   if (const auto *moduleSuffix =
649           args.getLastArg(clang::driver::options::OPT_module_suffix)) {
650     res.setModuleFileSuffix(moduleSuffix->getValue());
651   }
652 
653   // -f{no-}analyzed-objects-for-unparse
654   res.setUseAnalyzedObjectsForUnparse(args.hasFlag(
655       clang::driver::options::OPT_fanalyzed_objects_for_unparse,
656       clang::driver::options::OPT_fno_analyzed_objects_for_unparse, true));
657 
658   return diags.getNumErrors() == numErrorsBefore;
659 }
660 
661 /// Parses all diagnostics related arguments and populates the variables
662 /// options accordingly. Returns false if new errors are generated.
663 static bool parseDiagArgs(CompilerInvocation &res, llvm::opt::ArgList &args,
664                           clang::DiagnosticsEngine &diags) {
665   unsigned numErrorsBefore = diags.getNumErrors();
666 
667   // -Werror option
668   // TODO: Currently throws a Diagnostic for anything other than -W<error>,
669   // this has to change when other -W<opt>'s are supported.
670   if (args.hasArg(clang::driver::options::OPT_W_Joined)) {
671     const auto &wArgs =
672         args.getAllArgValues(clang::driver::options::OPT_W_Joined);
673     for (const auto &wArg : wArgs) {
674       if (wArg == "error") {
675         res.setWarnAsErr(true);
676       } else {
677         const unsigned diagID =
678             diags.getCustomDiagID(clang::DiagnosticsEngine::Error,
679                                   "Only `-Werror` is supported currently.");
680         diags.Report(diagID);
681       }
682     }
683   }
684 
685   // Default to off for `flang-new -fc1`.
686   res.getFrontendOpts().showColors =
687       parseShowColorsArgs(args, /*defaultDiagColor=*/false);
688 
689   return diags.getNumErrors() == numErrorsBefore;
690 }
691 
692 /// Parses all Dialect related arguments and populates the variables
693 /// options accordingly. Returns false if new errors are generated.
694 static bool parseDialectArgs(CompilerInvocation &res, llvm::opt::ArgList &args,
695                              clang::DiagnosticsEngine &diags) {
696   unsigned numErrorsBefore = diags.getNumErrors();
697 
698   // -fdefault* family
699   if (args.hasArg(clang::driver::options::OPT_fdefault_real_8)) {
700     res.getDefaultKinds().set_defaultRealKind(8);
701     res.getDefaultKinds().set_doublePrecisionKind(16);
702   }
703   if (args.hasArg(clang::driver::options::OPT_fdefault_integer_8)) {
704     res.getDefaultKinds().set_defaultIntegerKind(8);
705     res.getDefaultKinds().set_subscriptIntegerKind(8);
706     res.getDefaultKinds().set_sizeIntegerKind(8);
707     res.getDefaultKinds().set_defaultLogicalKind(8);
708   }
709   if (args.hasArg(clang::driver::options::OPT_fdefault_double_8)) {
710     if (!args.hasArg(clang::driver::options::OPT_fdefault_real_8)) {
711       // -fdefault-double-8 has to be used with -fdefault-real-8
712       // to be compatible with gfortran
713       const unsigned diagID = diags.getCustomDiagID(
714           clang::DiagnosticsEngine::Error,
715           "Use of `-fdefault-double-8` requires `-fdefault-real-8`");
716       diags.Report(diagID);
717     }
718     // https://gcc.gnu.org/onlinedocs/gfortran/Fortran-Dialect-Options.html
719     res.getDefaultKinds().set_doublePrecisionKind(8);
720   }
721   if (args.hasArg(clang::driver::options::OPT_flarge_sizes))
722     res.getDefaultKinds().set_sizeIntegerKind(8);
723 
724   // -fopenmp and -fopenacc
725   if (args.hasArg(clang::driver::options::OPT_fopenacc)) {
726     res.getFrontendOpts().features.Enable(
727         Fortran::common::LanguageFeature::OpenACC);
728   }
729   if (args.hasArg(clang::driver::options::OPT_fopenmp)) {
730     // By default OpenMP is set to 1.1 version
731     res.getLangOpts().OpenMPVersion = 11;
732     res.getFrontendOpts().features.Enable(
733         Fortran::common::LanguageFeature::OpenMP);
734     if (int Version = getLastArgIntValue(
735             args, clang::driver::options::OPT_fopenmp_version_EQ,
736             res.getLangOpts().OpenMPVersion, diags)) {
737       res.getLangOpts().OpenMPVersion = Version;
738     }
739     if (args.hasArg(clang::driver::options::OPT_fopenmp_is_target_device)) {
740       res.getLangOpts().OpenMPIsTargetDevice = 1;
741 
742       // Get OpenMP host file path if any and report if a non existent file is
743       // found
744       if (auto *arg = args.getLastArg(
745               clang::driver::options::OPT_fopenmp_host_ir_file_path)) {
746         res.getLangOpts().OMPHostIRFile = arg->getValue();
747         if (!llvm::sys::fs::exists(res.getLangOpts().OMPHostIRFile))
748           diags.Report(clang::diag::err_drv_omp_host_ir_file_not_found)
749               << res.getLangOpts().OMPHostIRFile;
750       }
751 
752       if (args.hasFlag(
753               clang::driver::options::OPT_fopenmp_assume_teams_oversubscription,
754               clang::driver::options::
755                   OPT_fno_openmp_assume_teams_oversubscription,
756               /*Default=*/false))
757         res.getLangOpts().OpenMPTeamSubscription = true;
758 
759       if (args.hasArg(
760               clang::driver::options::OPT_fopenmp_assume_no_thread_state))
761         res.getLangOpts().OpenMPNoThreadState = 1;
762 
763       if (args.hasArg(
764               clang::driver::options::OPT_fopenmp_assume_no_nested_parallelism))
765         res.getLangOpts().OpenMPNoNestedParallelism = 1;
766 
767       if (args.hasFlag(clang::driver::options::
768                            OPT_fopenmp_assume_threads_oversubscription,
769                        clang::driver::options::
770                            OPT_fno_openmp_assume_threads_oversubscription,
771                        /*Default=*/false))
772         res.getLangOpts().OpenMPThreadSubscription = true;
773 
774       if ((args.hasArg(clang::driver::options::OPT_fopenmp_target_debug) ||
775            args.hasArg(clang::driver::options::OPT_fopenmp_target_debug_EQ))) {
776         res.getLangOpts().OpenMPTargetDebug = getLastArgIntValue(
777             args, clang::driver::options::OPT_fopenmp_target_debug_EQ,
778             res.getLangOpts().OpenMPTargetDebug, diags);
779 
780         if (!res.getLangOpts().OpenMPTargetDebug &&
781             args.hasArg(clang::driver::options::OPT_fopenmp_target_debug))
782           res.getLangOpts().OpenMPTargetDebug = 1;
783       }
784     }
785 
786     switch (llvm::Triple(res.getTargetOpts().triple).getArch()) {
787     case llvm::Triple::nvptx:
788     case llvm::Triple::nvptx64:
789     case llvm::Triple::amdgcn:
790       if (!res.getLangOpts().OpenMPIsTargetDevice) {
791         const unsigned diagID = diags.getCustomDiagID(
792             clang::DiagnosticsEngine::Error,
793             "OpenMP AMDGPU/NVPTX is only prepared to deal with device code.");
794         diags.Report(diagID);
795       }
796       res.getLangOpts().OpenMPIsGPU = 1;
797       break;
798     default:
799       res.getLangOpts().OpenMPIsGPU = 0;
800       break;
801     }
802   }
803 
804   // -pedantic
805   if (args.hasArg(clang::driver::options::OPT_pedantic)) {
806     res.setEnableConformanceChecks();
807     res.setEnableUsageChecks();
808   }
809   // -std=f2018
810   // TODO: Set proper options when more fortran standards
811   // are supported.
812   if (args.hasArg(clang::driver::options::OPT_std_EQ)) {
813     auto standard = args.getLastArgValue(clang::driver::options::OPT_std_EQ);
814     // We only allow f2018 as the given standard
815     if (standard.equals("f2018")) {
816       res.setEnableConformanceChecks();
817     } else {
818       const unsigned diagID =
819           diags.getCustomDiagID(clang::DiagnosticsEngine::Error,
820                                 "Only -std=f2018 is allowed currently.");
821       diags.Report(diagID);
822     }
823   }
824   return diags.getNumErrors() == numErrorsBefore;
825 }
826 
827 /// Parses all floating point related arguments and populates the
828 /// CompilerInvocation accordingly.
829 /// Returns false if new errors are generated.
830 ///
831 /// \param [out] invoc Stores the processed arguments
832 /// \param [in] args The compiler invocation arguments to parse
833 /// \param [out] diags DiagnosticsEngine to report erros with
834 static bool parseFloatingPointArgs(CompilerInvocation &invoc,
835                                    llvm::opt::ArgList &args,
836                                    clang::DiagnosticsEngine &diags) {
837   LangOptions &opts = invoc.getLangOpts();
838 
839   if (const llvm::opt::Arg *a =
840           args.getLastArg(clang::driver::options::OPT_ffp_contract)) {
841     const llvm::StringRef val = a->getValue();
842     enum LangOptions::FPModeKind fpContractMode;
843 
844     if (val == "off")
845       fpContractMode = LangOptions::FPM_Off;
846     else if (val == "fast")
847       fpContractMode = LangOptions::FPM_Fast;
848     else {
849       diags.Report(clang::diag::err_drv_unsupported_option_argument)
850           << a->getSpelling() << val;
851       return false;
852     }
853 
854     opts.setFPContractMode(fpContractMode);
855   }
856 
857   if (args.getLastArg(clang::driver::options::OPT_menable_no_infinities)) {
858     opts.NoHonorInfs = true;
859   }
860 
861   if (args.getLastArg(clang::driver::options::OPT_menable_no_nans)) {
862     opts.NoHonorNaNs = true;
863   }
864 
865   if (args.getLastArg(clang::driver::options::OPT_fapprox_func)) {
866     opts.ApproxFunc = true;
867   }
868 
869   if (args.getLastArg(clang::driver::options::OPT_fno_signed_zeros)) {
870     opts.NoSignedZeros = true;
871   }
872 
873   if (args.getLastArg(clang::driver::options::OPT_mreassociate)) {
874     opts.AssociativeMath = true;
875   }
876 
877   if (args.getLastArg(clang::driver::options::OPT_freciprocal_math)) {
878     opts.ReciprocalMath = true;
879   }
880 
881   if (args.getLastArg(clang::driver::options::OPT_ffast_math)) {
882     opts.NoHonorInfs = true;
883     opts.NoHonorNaNs = true;
884     opts.AssociativeMath = true;
885     opts.ReciprocalMath = true;
886     opts.ApproxFunc = true;
887     opts.NoSignedZeros = true;
888     opts.setFPContractMode(LangOptions::FPM_Fast);
889   }
890 
891   return true;
892 }
893 
894 bool CompilerInvocation::createFromArgs(
895     CompilerInvocation &res, llvm::ArrayRef<const char *> commandLineArgs,
896     clang::DiagnosticsEngine &diags, const char *argv0) {
897 
898   bool success = true;
899 
900   // Set the default triple for this CompilerInvocation. This might be
901   // overridden by users with `-triple` (see the call to `ParseTargetArgs`
902   // below).
903   // NOTE: Like in Clang, it would be nice to use option marshalling
904   // for this so that the entire logic for setting-up the triple is in one
905   // place.
906   res.getTargetOpts().triple =
907       llvm::Triple::normalize(llvm::sys::getDefaultTargetTriple());
908 
909   // Parse the arguments
910   const llvm::opt::OptTable &opts = clang::driver::getDriverOptTable();
911   const unsigned includedFlagsBitmask = clang::driver::options::FC1Option;
912   unsigned missingArgIndex, missingArgCount;
913   llvm::opt::InputArgList args = opts.ParseArgs(
914       commandLineArgs, missingArgIndex, missingArgCount, includedFlagsBitmask);
915 
916   // Check for missing argument error.
917   if (missingArgCount) {
918     diags.Report(clang::diag::err_drv_missing_argument)
919         << args.getArgString(missingArgIndex) << missingArgCount;
920     success = false;
921   }
922 
923   // Issue errors on unknown arguments
924   for (const auto *a : args.filtered(clang::driver::options::OPT_UNKNOWN)) {
925     auto argString = a->getAsString(args);
926     std::string nearest;
927     if (opts.findNearest(argString, nearest, includedFlagsBitmask) > 1)
928       diags.Report(clang::diag::err_drv_unknown_argument) << argString;
929     else
930       diags.Report(clang::diag::err_drv_unknown_argument_with_suggestion)
931           << argString << nearest;
932     success = false;
933   }
934 
935   // -flang-experimental-hlfir
936   if (args.hasArg(clang::driver::options::OPT_flang_experimental_hlfir) ||
937       args.hasArg(clang::driver::options::OPT_emit_hlfir)) {
938     res.loweringOpts.setLowerToHighLevelFIR(true);
939   }
940 
941   if (args.hasArg(clang::driver::options::OPT_flang_experimental_polymorphism)) {
942     res.loweringOpts.setPolymorphicTypeImpl(true);
943   }
944 
945   success &= parseFrontendArgs(res.getFrontendOpts(), args, diags);
946   parseTargetArgs(res.getTargetOpts(), args);
947   parsePreprocessorArgs(res.getPreprocessorOpts(), args);
948   parseCodeGenArgs(res.getCodeGenOpts(), args, diags);
949   success &= parseDebugArgs(res.getCodeGenOpts(), args, diags);
950   success &= parseSemaArgs(res, args, diags);
951   success &= parseDialectArgs(res, args, diags);
952   success &= parseDiagArgs(res, args, diags);
953 
954   // Collect LLVM (-mllvm) and MLIR (-mmlir) options.
955   // NOTE: Try to avoid adding any options directly to `llvmArgs` or
956   // `mlirArgs`. Instead, you can use
957   //    * `-mllvm <your-llvm-option>`, or
958   //    * `-mmlir <your-mlir-option>`.
959   res.frontendOpts.llvmArgs =
960       args.getAllArgValues(clang::driver::options::OPT_mllvm);
961   res.frontendOpts.mlirArgs =
962       args.getAllArgValues(clang::driver::options::OPT_mmlir);
963 
964   success &= parseFloatingPointArgs(res, args, diags);
965 
966   // Set the string to be used as the return value of the COMPILER_OPTIONS
967   // intrinsic of iso_fortran_env. This is either passed in from the parent
968   // compiler driver invocation with an environment variable, or failing that
969   // set to the command line arguments of the frontend driver invocation.
970   res.allCompilerInvocOpts = std::string();
971   llvm::raw_string_ostream os(res.allCompilerInvocOpts);
972   char *compilerOptsEnv = std::getenv("FLANG_COMPILER_OPTIONS_STRING");
973   if (compilerOptsEnv != nullptr) {
974     os << compilerOptsEnv;
975   } else {
976     os << argv0 << ' ';
977     for (auto it = commandLineArgs.begin(), e = commandLineArgs.end(); it != e;
978          ++it) {
979       os << ' ' << *it;
980     }
981   }
982 
983   return success;
984 }
985 
986 void CompilerInvocation::collectMacroDefinitions() {
987   auto &ppOpts = this->getPreprocessorOpts();
988 
989   for (unsigned i = 0, n = ppOpts.macros.size(); i != n; ++i) {
990     llvm::StringRef macro = ppOpts.macros[i].first;
991     bool isUndef = ppOpts.macros[i].second;
992 
993     std::pair<llvm::StringRef, llvm::StringRef> macroPair = macro.split('=');
994     llvm::StringRef macroName = macroPair.first;
995     llvm::StringRef macroBody = macroPair.second;
996 
997     // For an #undef'd macro, we only care about the name.
998     if (isUndef) {
999       parserOpts.predefinitions.emplace_back(macroName.str(),
1000                                              std::optional<std::string>{});
1001       continue;
1002     }
1003 
1004     // For a #define'd macro, figure out the actual definition.
1005     if (macroName.size() == macro.size())
1006       macroBody = "1";
1007     else {
1008       // Note: GCC drops anything following an end-of-line character.
1009       llvm::StringRef::size_type end = macroBody.find_first_of("\n\r");
1010       macroBody = macroBody.substr(0, end);
1011     }
1012     parserOpts.predefinitions.emplace_back(
1013         macroName, std::optional<std::string>(macroBody.str()));
1014   }
1015 }
1016 
1017 void CompilerInvocation::setDefaultFortranOpts() {
1018   auto &fortranOptions = getFortranOpts();
1019 
1020   std::vector<std::string> searchDirectories{"."s};
1021   fortranOptions.searchDirectories = searchDirectories;
1022 
1023   // Add the location of omp_lib.h to the search directories. Currently this is
1024   // identical to the modules' directory.
1025   fortranOptions.searchDirectories.emplace_back(getOpenMPHeadersDir());
1026 
1027   fortranOptions.isFixedForm = false;
1028 }
1029 
1030 // TODO: When expanding this method, consider creating a dedicated API for
1031 // this. Also at some point we will need to differentiate between different
1032 // targets and add dedicated predefines for each.
1033 void CompilerInvocation::setDefaultPredefinitions() {
1034   auto &fortranOptions = getFortranOpts();
1035   const auto &frontendOptions = getFrontendOpts();
1036   // Populate the macro list with version numbers and other predefinitions.
1037   fortranOptions.predefinitions.emplace_back("__flang__", "1");
1038   fortranOptions.predefinitions.emplace_back("__flang_major__",
1039                                              FLANG_VERSION_MAJOR_STRING);
1040   fortranOptions.predefinitions.emplace_back("__flang_minor__",
1041                                              FLANG_VERSION_MINOR_STRING);
1042   fortranOptions.predefinitions.emplace_back("__flang_patchlevel__",
1043                                              FLANG_VERSION_PATCHLEVEL_STRING);
1044 
1045   // Add predefinitions based on extensions enabled
1046   if (frontendOptions.features.IsEnabled(
1047           Fortran::common::LanguageFeature::OpenACC)) {
1048     fortranOptions.predefinitions.emplace_back("_OPENACC", "202211");
1049   }
1050   if (frontendOptions.features.IsEnabled(
1051           Fortran::common::LanguageFeature::OpenMP)) {
1052     Fortran::common::setOpenMPMacro(getLangOpts().OpenMPVersion,
1053                                     fortranOptions.predefinitions);
1054   }
1055   llvm::Triple targetTriple{llvm::Triple(this->targetOpts.triple)};
1056   if (targetTriple.getArch() == llvm::Triple::ArchType::x86_64) {
1057     fortranOptions.predefinitions.emplace_back("__x86_64__", "1");
1058     fortranOptions.predefinitions.emplace_back("__x86_64", "1");
1059   }
1060 }
1061 
1062 void CompilerInvocation::setFortranOpts() {
1063   auto &fortranOptions = getFortranOpts();
1064   const auto &frontendOptions = getFrontendOpts();
1065   const auto &preprocessorOptions = getPreprocessorOpts();
1066   auto &moduleDirJ = getModuleDir();
1067 
1068   if (frontendOptions.fortranForm != FortranForm::Unknown) {
1069     fortranOptions.isFixedForm =
1070         frontendOptions.fortranForm == FortranForm::FixedForm;
1071   }
1072   fortranOptions.fixedFormColumns = frontendOptions.fixedFormColumns;
1073 
1074   fortranOptions.features = frontendOptions.features;
1075   fortranOptions.encoding = frontendOptions.encoding;
1076 
1077   // Adding search directories specified by -I
1078   fortranOptions.searchDirectories.insert(
1079       fortranOptions.searchDirectories.end(),
1080       preprocessorOptions.searchDirectoriesFromDashI.begin(),
1081       preprocessorOptions.searchDirectoriesFromDashI.end());
1082 
1083   // Add the ordered list of -intrinsic-modules-path
1084   fortranOptions.searchDirectories.insert(
1085       fortranOptions.searchDirectories.end(),
1086       preprocessorOptions.searchDirectoriesFromIntrModPath.begin(),
1087       preprocessorOptions.searchDirectoriesFromIntrModPath.end());
1088 
1089   //  Add the default intrinsic module directory
1090   fortranOptions.intrinsicModuleDirectories.emplace_back(getIntrinsicDir());
1091 
1092   // Add the directory supplied through -J/-module-dir to the list of search
1093   // directories
1094   if (moduleDirJ != ".")
1095     fortranOptions.searchDirectories.emplace_back(moduleDirJ);
1096 
1097   if (frontendOptions.instrumentedParse)
1098     fortranOptions.instrumentedParse = true;
1099 
1100   if (frontendOptions.showColors)
1101     fortranOptions.showColors = true;
1102 
1103   if (frontendOptions.needProvenanceRangeToCharBlockMappings)
1104     fortranOptions.needProvenanceRangeToCharBlockMappings = true;
1105 
1106   if (getEnableConformanceChecks())
1107     fortranOptions.features.WarnOnAllNonstandard();
1108 
1109   if (getEnableUsageChecks())
1110     fortranOptions.features.WarnOnAllUsage();
1111 }
1112 
1113 void CompilerInvocation::setSemanticsOpts(
1114     Fortran::parser::AllCookedSources &allCookedSources) {
1115   auto &fortranOptions = getFortranOpts();
1116 
1117   semanticsContext = std::make_unique<semantics::SemanticsContext>(
1118       getDefaultKinds(), fortranOptions.features, allCookedSources);
1119 
1120   semanticsContext->set_moduleDirectory(getModuleDir())
1121       .set_searchDirectories(fortranOptions.searchDirectories)
1122       .set_intrinsicModuleDirectories(fortranOptions.intrinsicModuleDirectories)
1123       .set_warningsAreErrors(getWarnAsErr())
1124       .set_moduleFileSuffix(getModuleFileSuffix());
1125 
1126   llvm::Triple targetTriple{llvm::Triple(this->targetOpts.triple)};
1127   // FIXME: Handle real(3) ?
1128   if (targetTriple.getArch() != llvm::Triple::ArchType::x86_64) {
1129     semanticsContext->targetCharacteristics().DisableType(
1130         Fortran::common::TypeCategory::Real, /*kind=*/10);
1131   }
1132 
1133   std::string version = Fortran::common::getFlangFullVersion();
1134   semanticsContext->targetCharacteristics()
1135       .set_compilerOptionsString(allCompilerInvocOpts)
1136       .set_compilerVersionString(version);
1137 
1138   if (targetTriple.isPPC())
1139     semanticsContext->targetCharacteristics().set_isPPC(true);
1140 }
1141 
1142 /// Set \p loweringOptions controlling lowering behavior based
1143 /// on the \p optimizationLevel.
1144 void CompilerInvocation::setLoweringOptions() {
1145   const CodeGenOptions &codegenOpts = getCodeGenOpts();
1146 
1147   // Lower TRANSPOSE as a runtime call under -O0.
1148   loweringOpts.setOptimizeTranspose(codegenOpts.OptimizationLevel > 0);
1149 
1150   const LangOptions &langOptions = getLangOpts();
1151   Fortran::common::MathOptionsBase &mathOpts = loweringOpts.getMathOptions();
1152   // TODO: when LangOptions are finalized, we can represent
1153   //       the math related options using Fortran::commmon::MathOptionsBase,
1154   //       so that we can just copy it into LoweringOptions.
1155   mathOpts
1156       .setFPContractEnabled(langOptions.getFPContractMode() ==
1157                             LangOptions::FPM_Fast)
1158       .setNoHonorInfs(langOptions.NoHonorInfs)
1159       .setNoHonorNaNs(langOptions.NoHonorNaNs)
1160       .setApproxFunc(langOptions.ApproxFunc)
1161       .setNoSignedZeros(langOptions.NoSignedZeros)
1162       .setAssociativeMath(langOptions.AssociativeMath)
1163       .setReciprocalMath(langOptions.ReciprocalMath);
1164 }
1165