xref: /llvm-project/flang/lib/Frontend/CompilerInvocation.cpp (revision b5e93e390c06602cb03121ad875e2855253e2937)
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/Frontend/CodeGenOptions.h"
16 #include "flang/Frontend/PreprocessorOptions.h"
17 #include "flang/Frontend/TargetOptions.h"
18 #include "flang/Semantics/semantics.h"
19 #include "flang/Version.inc"
20 #include "clang/Basic/AllDiagnostics.h"
21 #include "clang/Basic/DiagnosticDriver.h"
22 #include "clang/Basic/DiagnosticOptions.h"
23 #include "clang/Driver/DriverDiagnostic.h"
24 #include "clang/Driver/OptionUtils.h"
25 #include "clang/Driver/Options.h"
26 #include "llvm/ADT/StringRef.h"
27 #include "llvm/ADT/StringSwitch.h"
28 #include "llvm/ADT/Triple.h"
29 #include "llvm/Option/Arg.h"
30 #include "llvm/Option/ArgList.h"
31 #include "llvm/Option/OptTable.h"
32 #include "llvm/Support/FileSystem.h"
33 #include "llvm/Support/FileUtilities.h"
34 #include "llvm/Support/Host.h"
35 #include "llvm/Support/Path.h"
36 #include "llvm/Support/Process.h"
37 #include "llvm/Support/raw_ostream.h"
38 #include <memory>
39 
40 using namespace Fortran::frontend;
41 
42 //===----------------------------------------------------------------------===//
43 // Initialization.
44 //===----------------------------------------------------------------------===//
45 CompilerInvocationBase::CompilerInvocationBase()
46     : diagnosticOpts(new clang::DiagnosticOptions()),
47       preprocessorOpts(new PreprocessorOptions()) {}
48 
49 CompilerInvocationBase::CompilerInvocationBase(const CompilerInvocationBase &x)
50     : diagnosticOpts(new clang::DiagnosticOptions(x.getDiagnosticOpts())),
51       preprocessorOpts(new PreprocessorOptions(x.getPreprocessorOpts())) {}
52 
53 CompilerInvocationBase::~CompilerInvocationBase() = default;
54 
55 //===----------------------------------------------------------------------===//
56 // Deserialization (from args)
57 //===----------------------------------------------------------------------===//
58 static bool parseShowColorsArgs(const llvm::opt::ArgList &args,
59                                 bool defaultColor = true) {
60   // Color diagnostics default to auto ("on" if terminal supports) in the
61   // compiler driver `flang-new` but default to off in the frontend driver
62   // `flang-new -fc1`, needing an explicit OPT_fdiagnostics_color.
63   // Support both clang's -f[no-]color-diagnostics and gcc's
64   // -f[no-]diagnostics-colors[=never|always|auto].
65   enum {
66     Colors_On,
67     Colors_Off,
68     Colors_Auto
69   } showColors = defaultColor ? Colors_Auto : Colors_Off;
70 
71   for (auto *a : args) {
72     const llvm::opt::Option &opt = a->getOption();
73     if (opt.matches(clang::driver::options::OPT_fcolor_diagnostics)) {
74       showColors = Colors_On;
75     } else if (opt.matches(clang::driver::options::OPT_fno_color_diagnostics)) {
76       showColors = Colors_Off;
77     } else if (opt.matches(clang::driver::options::OPT_fdiagnostics_color_EQ)) {
78       llvm::StringRef value(a->getValue());
79       if (value == "always")
80         showColors = Colors_On;
81       else if (value == "never")
82         showColors = Colors_Off;
83       else if (value == "auto")
84         showColors = Colors_Auto;
85     }
86   }
87 
88   return showColors == Colors_On ||
89          (showColors == Colors_Auto &&
90           llvm::sys::Process::StandardErrHasColors());
91 }
92 
93 /// Extracts the optimisation level from \a args.
94 static unsigned getOptimizationLevel(llvm::opt::ArgList &args,
95                                      clang::DiagnosticsEngine &diags) {
96   unsigned defaultOpt = llvm::CodeGenOpt::None;
97 
98   if (llvm::opt::Arg *a =
99           args.getLastArg(clang::driver::options::OPT_O_Group)) {
100     if (a->getOption().matches(clang::driver::options::OPT_O0))
101       return llvm::CodeGenOpt::None;
102 
103     assert(a->getOption().matches(clang::driver::options::OPT_O));
104 
105     return getLastArgIntValue(args, clang::driver::options::OPT_O, defaultOpt,
106                               diags);
107   }
108 
109   return defaultOpt;
110 }
111 
112 bool Fortran::frontend::parseDiagnosticArgs(clang::DiagnosticOptions &opts,
113                                             llvm::opt::ArgList &args) {
114   opts.ShowColors = parseShowColorsArgs(args);
115 
116   return true;
117 }
118 
119 static void parseCodeGenArgs(Fortran::frontend::CodeGenOptions &opts,
120                              llvm::opt::ArgList &args,
121                              clang::DiagnosticsEngine &diags) {
122   opts.OptimizationLevel = getOptimizationLevel(args, diags);
123 
124   if (args.hasFlag(clang::driver::options::OPT_fdebug_pass_manager,
125                    clang::driver::options::OPT_fno_debug_pass_manager, false))
126     opts.DebugPassManager = 1;
127 
128   // -mrelocation-model option.
129   if (const llvm::opt::Arg *A =
130           args.getLastArg(clang::driver::options::OPT_mrelocation_model)) {
131     llvm::StringRef ModelName = A->getValue();
132     auto RM = llvm::StringSwitch<llvm::Optional<llvm::Reloc::Model>>(ModelName)
133                   .Case("static", llvm::Reloc::Static)
134                   .Case("pic", llvm::Reloc::PIC_)
135                   .Case("dynamic-no-pic", llvm::Reloc::DynamicNoPIC)
136                   .Case("ropi", llvm::Reloc::ROPI)
137                   .Case("rwpi", llvm::Reloc::RWPI)
138                   .Case("ropi-rwpi", llvm::Reloc::ROPI_RWPI)
139                   .Default(llvm::None);
140     if (RM.has_value())
141       opts.setRelocationModel(*RM);
142     else
143       diags.Report(clang::diag::err_drv_invalid_value)
144           << A->getAsString(args) << ModelName;
145   }
146 
147   // -pic-level and -pic-is-pie option.
148   if (int PICLevel = getLastArgIntValue(
149           args, clang::driver::options::OPT_pic_level, 0, diags)) {
150     if (PICLevel > 2)
151       diags.Report(clang::diag::err_drv_invalid_value)
152           << args.getLastArg(clang::driver::options::OPT_pic_level)
153                  ->getAsString(args)
154           << PICLevel;
155 
156     opts.PICLevel = PICLevel;
157     if (args.hasArg(clang::driver::options::OPT_pic_is_pie))
158       opts.IsPIE = 1;
159   }
160 }
161 
162 /// Parses all target input arguments and populates the target
163 /// options accordingly.
164 ///
165 /// \param [in] opts The target options instance to update
166 /// \param [in] args The list of input arguments (from the compiler invocation)
167 static void parseTargetArgs(TargetOptions &opts, llvm::opt::ArgList &args) {
168   if (const llvm::opt::Arg *a =
169           args.getLastArg(clang::driver::options::OPT_triple))
170     opts.triple = a->getValue();
171 }
172 
173 // Tweak the frontend configuration based on the frontend action
174 static void setUpFrontendBasedOnAction(FrontendOptions &opts) {
175   if (opts.programAction == DebugDumpParsingLog)
176     opts.instrumentedParse = true;
177 
178   if (opts.programAction == DebugDumpProvenance ||
179       opts.programAction == Fortran::frontend::GetDefinition)
180     opts.needProvenanceRangeToCharBlockMappings = true;
181 }
182 
183 /// Parse the argument specified for the -fconvert=<value> option
184 static std::optional<const char *> parseConvertArg(const char *s) {
185   return llvm::StringSwitch<std::optional<const char *>>(s)
186       .Case("unknown", "UNKNOWN")
187       .Case("native", "NATIVE")
188       .Case("little-endian", "LITTLE_ENDIAN")
189       .Case("big-endian", "BIG_ENDIAN")
190       .Case("swap", "SWAP")
191       .Default(std::nullopt);
192 }
193 
194 static bool parseFrontendArgs(FrontendOptions &opts, llvm::opt::ArgList &args,
195                               clang::DiagnosticsEngine &diags) {
196   unsigned numErrorsBefore = diags.getNumErrors();
197 
198   // By default the frontend driver creates a ParseSyntaxOnly action.
199   opts.programAction = ParseSyntaxOnly;
200 
201   // Treat multiple action options as an invocation error. Note that `clang
202   // -cc1` does accept multiple action options, but will only consider the
203   // rightmost one.
204   if (args.hasMultipleArgs(clang::driver::options::OPT_Action_Group)) {
205     const unsigned diagID = diags.getCustomDiagID(
206         clang::DiagnosticsEngine::Error, "Only one action option is allowed");
207     diags.Report(diagID);
208     return false;
209   }
210 
211   // Identify the action (i.e. opts.ProgramAction)
212   if (const llvm::opt::Arg *a =
213           args.getLastArg(clang::driver::options::OPT_Action_Group)) {
214     switch (a->getOption().getID()) {
215     default: {
216       llvm_unreachable("Invalid option in group!");
217     }
218     case clang::driver::options::OPT_test_io:
219       opts.programAction = InputOutputTest;
220       break;
221     case clang::driver::options::OPT_E:
222       opts.programAction = PrintPreprocessedInput;
223       break;
224     case clang::driver::options::OPT_fsyntax_only:
225       opts.programAction = ParseSyntaxOnly;
226       break;
227     case clang::driver::options::OPT_emit_mlir:
228       opts.programAction = EmitMLIR;
229       break;
230     case clang::driver::options::OPT_emit_llvm:
231       opts.programAction = EmitLLVM;
232       break;
233     case clang::driver::options::OPT_emit_llvm_bc:
234       opts.programAction = EmitLLVMBitcode;
235       break;
236     case clang::driver::options::OPT_emit_obj:
237       opts.programAction = EmitObj;
238       break;
239     case clang::driver::options::OPT_S:
240       opts.programAction = EmitAssembly;
241       break;
242     case clang::driver::options::OPT_fdebug_unparse:
243       opts.programAction = DebugUnparse;
244       break;
245     case clang::driver::options::OPT_fdebug_unparse_no_sema:
246       opts.programAction = DebugUnparseNoSema;
247       break;
248     case clang::driver::options::OPT_fdebug_unparse_with_symbols:
249       opts.programAction = DebugUnparseWithSymbols;
250       break;
251     case clang::driver::options::OPT_fdebug_dump_symbols:
252       opts.programAction = DebugDumpSymbols;
253       break;
254     case clang::driver::options::OPT_fdebug_dump_parse_tree:
255       opts.programAction = DebugDumpParseTree;
256       break;
257     case clang::driver::options::OPT_fdebug_dump_pft:
258       opts.programAction = DebugDumpPFT;
259       break;
260     case clang::driver::options::OPT_fdebug_dump_all:
261       opts.programAction = DebugDumpAll;
262       break;
263     case clang::driver::options::OPT_fdebug_dump_parse_tree_no_sema:
264       opts.programAction = DebugDumpParseTreeNoSema;
265       break;
266     case clang::driver::options::OPT_fdebug_dump_provenance:
267       opts.programAction = DebugDumpProvenance;
268       break;
269     case clang::driver::options::OPT_fdebug_dump_parsing_log:
270       opts.programAction = DebugDumpParsingLog;
271       break;
272     case clang::driver::options::OPT_fdebug_measure_parse_tree:
273       opts.programAction = DebugMeasureParseTree;
274       break;
275     case clang::driver::options::OPT_fdebug_pre_fir_tree:
276       opts.programAction = DebugPreFIRTree;
277       break;
278     case clang::driver::options::OPT_fget_symbols_sources:
279       opts.programAction = GetSymbolsSources;
280       break;
281     case clang::driver::options::OPT_fget_definition:
282       opts.programAction = GetDefinition;
283       break;
284     case clang::driver::options::OPT_init_only:
285       opts.programAction = InitOnly;
286       break;
287 
288       // TODO:
289       // case clang::driver::options::OPT_emit_llvm:
290       // case clang::driver::options::OPT_emit_llvm_only:
291       // case clang::driver::options::OPT_emit_codegen_only:
292       // case clang::driver::options::OPT_emit_module:
293       // (...)
294     }
295 
296     // Parse the values provided with `-fget-definition` (there should be 3
297     // integers)
298     if (llvm::opt::OptSpecifier(a->getOption().getID()) ==
299         clang::driver::options::OPT_fget_definition) {
300       unsigned optVals[3] = {0, 0, 0};
301 
302       for (unsigned i = 0; i < 3; i++) {
303         llvm::StringRef val = a->getValue(i);
304 
305         if (val.getAsInteger(10, optVals[i])) {
306           // A non-integer was encountered - that's an error.
307           diags.Report(clang::diag::err_drv_invalid_value)
308               << a->getOption().getName() << val;
309           break;
310         }
311       }
312       opts.getDefVals.line = optVals[0];
313       opts.getDefVals.startColumn = optVals[1];
314       opts.getDefVals.endColumn = optVals[2];
315     }
316   }
317 
318   // Parsing -load <dsopath> option and storing shared object path
319   if (llvm::opt::Arg *a = args.getLastArg(clang::driver::options::OPT_load)) {
320     opts.plugins.push_back(a->getValue());
321   }
322 
323   // Parsing -plugin <name> option and storing plugin name and setting action
324   if (const llvm::opt::Arg *a =
325           args.getLastArg(clang::driver::options::OPT_plugin)) {
326     opts.programAction = PluginAction;
327     opts.actionName = a->getValue();
328   }
329 
330   opts.outputFile = args.getLastArgValue(clang::driver::options::OPT_o);
331   opts.showHelp = args.hasArg(clang::driver::options::OPT_help);
332   opts.showVersion = args.hasArg(clang::driver::options::OPT_version);
333 
334   // Get the input kind (from the value passed via `-x`)
335   InputKind dashX(Language::Unknown);
336   if (const llvm::opt::Arg *a =
337           args.getLastArg(clang::driver::options::OPT_x)) {
338     llvm::StringRef xValue = a->getValue();
339     // Principal languages.
340     dashX = llvm::StringSwitch<InputKind>(xValue)
341                 // Flang does not differentiate between pre-processed and not
342                 // pre-processed inputs.
343                 .Case("f95", Language::Fortran)
344                 .Case("f95-cpp-input", Language::Fortran)
345                 .Default(Language::Unknown);
346 
347     // Flang's intermediate representations.
348     if (dashX.isUnknown())
349       dashX = llvm::StringSwitch<InputKind>(xValue)
350                   .Case("ir", Language::LLVM_IR)
351                   .Case("fir", Language::MLIR)
352                   .Case("mlir", Language::MLIR)
353                   .Default(Language::Unknown);
354 
355     if (dashX.isUnknown())
356       diags.Report(clang::diag::err_drv_invalid_value)
357           << a->getAsString(args) << a->getValue();
358   }
359 
360   // Collect the input files and save them in our instance of FrontendOptions.
361   std::vector<std::string> inputs =
362       args.getAllArgValues(clang::driver::options::OPT_INPUT);
363   opts.inputs.clear();
364   if (inputs.empty())
365     // '-' is the default input if none is given.
366     inputs.push_back("-");
367   for (unsigned i = 0, e = inputs.size(); i != e; ++i) {
368     InputKind ik = dashX;
369     if (ik.isUnknown()) {
370       ik = FrontendOptions::getInputKindForExtension(
371           llvm::StringRef(inputs[i]).rsplit('.').second);
372       if (ik.isUnknown())
373         ik = Language::Unknown;
374       if (i == 0)
375         dashX = ik;
376     }
377 
378     opts.inputs.emplace_back(std::move(inputs[i]), ik);
379   }
380 
381   // Set fortranForm based on options -ffree-form and -ffixed-form.
382   if (const auto *arg =
383           args.getLastArg(clang::driver::options::OPT_ffixed_form,
384                           clang::driver::options::OPT_ffree_form)) {
385     opts.fortranForm =
386         arg->getOption().matches(clang::driver::options::OPT_ffixed_form)
387             ? FortranForm::FixedForm
388             : FortranForm::FreeForm;
389   }
390 
391   // Set fixedFormColumns based on -ffixed-line-length=<value>
392   if (const auto *arg =
393           args.getLastArg(clang::driver::options::OPT_ffixed_line_length_EQ)) {
394     llvm::StringRef argValue = llvm::StringRef(arg->getValue());
395     std::int64_t columns = -1;
396     if (argValue == "none") {
397       columns = 0;
398     } else if (argValue.getAsInteger(/*Radix=*/10, columns)) {
399       columns = -1;
400     }
401     if (columns < 0) {
402       diags.Report(clang::diag::err_drv_negative_columns)
403           << arg->getOption().getName() << arg->getValue();
404     } else if (columns == 0) {
405       opts.fixedFormColumns = 1000000;
406     } else if (columns < 7) {
407       diags.Report(clang::diag::err_drv_small_columns)
408           << arg->getOption().getName() << arg->getValue() << "7";
409     } else {
410       opts.fixedFormColumns = columns;
411     }
412   }
413 
414   // Set conversion based on -fconvert=<value>
415   if (const auto *arg =
416           args.getLastArg(clang::driver::options::OPT_fconvert_EQ)) {
417     const char *argValue = arg->getValue();
418     if (auto convert = parseConvertArg(argValue))
419       opts.envDefaults.push_back({"FORT_CONVERT", *convert});
420     else
421       diags.Report(clang::diag::err_drv_invalid_value)
422           << arg->getAsString(args) << argValue;
423   }
424 
425   // -f{no-}implicit-none
426   opts.features.Enable(
427       Fortran::common::LanguageFeature::ImplicitNoneTypeAlways,
428       args.hasFlag(clang::driver::options::OPT_fimplicit_none,
429                    clang::driver::options::OPT_fno_implicit_none, false));
430 
431   // -f{no-}backslash
432   opts.features.Enable(Fortran::common::LanguageFeature::BackslashEscapes,
433                        args.hasFlag(clang::driver::options::OPT_fbackslash,
434                                     clang::driver::options::OPT_fno_backslash,
435                                     false));
436 
437   // -f{no-}logical-abbreviations
438   opts.features.Enable(
439       Fortran::common::LanguageFeature::LogicalAbbreviations,
440       args.hasFlag(clang::driver::options::OPT_flogical_abbreviations,
441                    clang::driver::options::OPT_fno_logical_abbreviations,
442                    false));
443 
444   // -f{no-}xor-operator
445   opts.features.Enable(
446       Fortran::common::LanguageFeature::XOROperator,
447       args.hasFlag(clang::driver::options::OPT_fxor_operator,
448                    clang::driver::options::OPT_fno_xor_operator, false));
449 
450   // -fno-automatic
451   if (args.hasArg(clang::driver::options::OPT_fno_automatic)) {
452     opts.features.Enable(Fortran::common::LanguageFeature::DefaultSave);
453   }
454 
455   if (args.hasArg(
456           clang::driver::options::OPT_falternative_parameter_statement)) {
457     opts.features.Enable(Fortran::common::LanguageFeature::OldStyleParameter);
458   }
459   if (const llvm::opt::Arg *arg =
460           args.getLastArg(clang::driver::options::OPT_finput_charset_EQ)) {
461     llvm::StringRef argValue = arg->getValue();
462     if (argValue == "utf-8") {
463       opts.encoding = Fortran::parser::Encoding::UTF_8;
464     } else if (argValue == "latin-1") {
465       opts.encoding = Fortran::parser::Encoding::LATIN_1;
466     } else {
467       diags.Report(clang::diag::err_drv_invalid_value)
468           << arg->getAsString(args) << argValue;
469     }
470   }
471 
472   setUpFrontendBasedOnAction(opts);
473   opts.dashX = dashX;
474 
475   return diags.getNumErrors() == numErrorsBefore;
476 }
477 
478 // Generate the path to look for intrinsic modules
479 static std::string getIntrinsicDir() {
480   // TODO: Find a system independent API
481   llvm::SmallString<128> driverPath;
482   driverPath.assign(llvm::sys::fs::getMainExecutable(nullptr, nullptr));
483   llvm::sys::path::remove_filename(driverPath);
484   driverPath.append("/../include/flang/");
485   return std::string(driverPath);
486 }
487 
488 // Generate the path to look for OpenMP headers
489 static std::string getOpenMPHeadersDir() {
490   llvm::SmallString<128> includePath;
491   includePath.assign(llvm::sys::fs::getMainExecutable(nullptr, nullptr));
492   llvm::sys::path::remove_filename(includePath);
493   includePath.append("/../include/flang/OpenMP/");
494   return std::string(includePath);
495 }
496 
497 /// Parses all preprocessor input arguments and populates the preprocessor
498 /// options accordingly.
499 ///
500 /// \param [in] opts The preprocessor options instance
501 /// \param [out] args The list of input arguments
502 static void parsePreprocessorArgs(Fortran::frontend::PreprocessorOptions &opts,
503                                   llvm::opt::ArgList &args) {
504   // Add macros from the command line.
505   for (const auto *currentArg : args.filtered(clang::driver::options::OPT_D,
506                                               clang::driver::options::OPT_U)) {
507     if (currentArg->getOption().matches(clang::driver::options::OPT_D)) {
508       opts.addMacroDef(currentArg->getValue());
509     } else {
510       opts.addMacroUndef(currentArg->getValue());
511     }
512   }
513 
514   // Add the ordered list of -I's.
515   for (const auto *currentArg : args.filtered(clang::driver::options::OPT_I))
516     opts.searchDirectoriesFromDashI.emplace_back(currentArg->getValue());
517 
518   // Prepend the ordered list of -intrinsic-modules-path
519   // to the default location to search.
520   for (const auto *currentArg :
521        args.filtered(clang::driver::options::OPT_fintrinsic_modules_path))
522     opts.searchDirectoriesFromIntrModPath.emplace_back(currentArg->getValue());
523 
524   // -cpp/-nocpp
525   if (const auto *currentArg = args.getLastArg(
526           clang::driver::options::OPT_cpp, clang::driver::options::OPT_nocpp))
527     opts.macrosFlag =
528         (currentArg->getOption().matches(clang::driver::options::OPT_cpp))
529             ? PPMacrosFlag::Include
530             : PPMacrosFlag::Exclude;
531 
532   opts.noReformat = args.hasArg(clang::driver::options::OPT_fno_reformat);
533   opts.noLineDirectives = args.hasArg(clang::driver::options::OPT_P);
534 }
535 
536 /// Parses all semantic related arguments and populates the variables
537 /// options accordingly. Returns false if new errors are generated.
538 static bool parseSemaArgs(CompilerInvocation &res, llvm::opt::ArgList &args,
539                           clang::DiagnosticsEngine &diags) {
540   unsigned numErrorsBefore = diags.getNumErrors();
541 
542   // -J/module-dir option
543   auto moduleDirList =
544       args.getAllArgValues(clang::driver::options::OPT_module_dir);
545   // User can only specify -J/-module-dir once
546   // https://gcc.gnu.org/onlinedocs/gfortran/Directory-Options.html
547   if (moduleDirList.size() > 1) {
548     const unsigned diagID =
549         diags.getCustomDiagID(clang::DiagnosticsEngine::Error,
550                               "Only one '-module-dir/-J' option allowed");
551     diags.Report(diagID);
552   }
553   if (moduleDirList.size() == 1)
554     res.setModuleDir(moduleDirList[0]);
555 
556   // -fdebug-module-writer option
557   if (args.hasArg(clang::driver::options::OPT_fdebug_module_writer)) {
558     res.setDebugModuleDir(true);
559   }
560 
561   // -module-suffix
562   if (const auto *moduleSuffix =
563           args.getLastArg(clang::driver::options::OPT_module_suffix)) {
564     res.setModuleFileSuffix(moduleSuffix->getValue());
565   }
566 
567   // -f{no-}analyzed-objects-for-unparse
568   res.setUseAnalyzedObjectsForUnparse(args.hasFlag(
569       clang::driver::options::OPT_fanalyzed_objects_for_unparse,
570       clang::driver::options::OPT_fno_analyzed_objects_for_unparse, true));
571 
572   return diags.getNumErrors() == numErrorsBefore;
573 }
574 
575 /// Parses all diagnostics related arguments and populates the variables
576 /// options accordingly. Returns false if new errors are generated.
577 static bool parseDiagArgs(CompilerInvocation &res, llvm::opt::ArgList &args,
578                           clang::DiagnosticsEngine &diags) {
579   unsigned numErrorsBefore = diags.getNumErrors();
580 
581   // -Werror option
582   // TODO: Currently throws a Diagnostic for anything other than -W<error>,
583   // this has to change when other -W<opt>'s are supported.
584   if (args.hasArg(clang::driver::options::OPT_W_Joined)) {
585     if (args.getLastArgValue(clang::driver::options::OPT_W_Joined)
586             .equals("error")) {
587       res.setWarnAsErr(true);
588     } else {
589       const unsigned diagID =
590           diags.getCustomDiagID(clang::DiagnosticsEngine::Error,
591                                 "Only `-Werror` is supported currently.");
592       diags.Report(diagID);
593     }
594   }
595 
596   // Default to off for `flang-new -fc1`.
597   res.getFrontendOpts().showColors =
598       parseShowColorsArgs(args, /*defaultDiagColor=*/false);
599 
600   return diags.getNumErrors() == numErrorsBefore;
601 }
602 
603 /// Parses all Dialect related arguments and populates the variables
604 /// options accordingly. Returns false if new errors are generated.
605 static bool parseDialectArgs(CompilerInvocation &res, llvm::opt::ArgList &args,
606                              clang::DiagnosticsEngine &diags) {
607   unsigned numErrorsBefore = diags.getNumErrors();
608 
609   // -fdefault* family
610   if (args.hasArg(clang::driver::options::OPT_fdefault_real_8)) {
611     res.getDefaultKinds().set_defaultRealKind(8);
612     res.getDefaultKinds().set_doublePrecisionKind(16);
613   }
614   if (args.hasArg(clang::driver::options::OPT_fdefault_integer_8)) {
615     res.getDefaultKinds().set_defaultIntegerKind(8);
616     res.getDefaultKinds().set_subscriptIntegerKind(8);
617     res.getDefaultKinds().set_sizeIntegerKind(8);
618   }
619   if (args.hasArg(clang::driver::options::OPT_fdefault_double_8)) {
620     if (!args.hasArg(clang::driver::options::OPT_fdefault_real_8)) {
621       // -fdefault-double-8 has to be used with -fdefault-real-8
622       // to be compatible with gfortran
623       const unsigned diagID = diags.getCustomDiagID(
624           clang::DiagnosticsEngine::Error,
625           "Use of `-fdefault-double-8` requires `-fdefault-real-8`");
626       diags.Report(diagID);
627     }
628     // https://gcc.gnu.org/onlinedocs/gfortran/Fortran-Dialect-Options.html
629     res.getDefaultKinds().set_doublePrecisionKind(8);
630   }
631   if (args.hasArg(clang::driver::options::OPT_flarge_sizes))
632     res.getDefaultKinds().set_sizeIntegerKind(8);
633 
634   // -fopenmp and -fopenacc
635   if (args.hasArg(clang::driver::options::OPT_fopenacc)) {
636     res.getFrontendOpts().features.Enable(
637         Fortran::common::LanguageFeature::OpenACC);
638   }
639   if (args.hasArg(clang::driver::options::OPT_fopenmp)) {
640     res.getFrontendOpts().features.Enable(
641         Fortran::common::LanguageFeature::OpenMP);
642   }
643 
644   // -pedantic
645   if (args.hasArg(clang::driver::options::OPT_pedantic)) {
646     res.setEnableConformanceChecks();
647   }
648   // -std=f2018 (currently this implies -pedantic)
649   // TODO: Set proper options when more fortran standards
650   // are supported.
651   if (args.hasArg(clang::driver::options::OPT_std_EQ)) {
652     auto standard = args.getLastArgValue(clang::driver::options::OPT_std_EQ);
653     // We only allow f2018 as the given standard
654     if (standard.equals("f2018")) {
655       res.setEnableConformanceChecks();
656     } else {
657       const unsigned diagID =
658           diags.getCustomDiagID(clang::DiagnosticsEngine::Error,
659                                 "Only -std=f2018 is allowed currently.");
660       diags.Report(diagID);
661     }
662   }
663   return diags.getNumErrors() == numErrorsBefore;
664 }
665 
666 /// Parses all floating point related arguments and populates the
667 /// CompilerInvocation accordingly.
668 /// Returns false if new errors are generated.
669 ///
670 /// \param [out] invoc Stores the processed arguments
671 /// \param [in] args The compiler invocation arguments to parse
672 /// \param [out] diags DiagnosticsEngine to report erros with
673 static bool parseFloatingPointArgs(CompilerInvocation &invoc,
674                                    llvm::opt::ArgList &args,
675                                    clang::DiagnosticsEngine &diags) {
676   LangOptions &opts = invoc.getLangOpts();
677   const unsigned diagUnimplemented = diags.getCustomDiagID(
678       clang::DiagnosticsEngine::Warning, "%0 is not currently implemented");
679 
680   if (const llvm::opt::Arg *a =
681           args.getLastArg(clang::driver::options::OPT_ffp_contract)) {
682     const llvm::StringRef val = a->getValue();
683     enum LangOptions::FPModeKind fpContractMode;
684 
685     if (val == "off")
686       fpContractMode = LangOptions::FPM_Off;
687     else if (val == "fast")
688       fpContractMode = LangOptions::FPM_Fast;
689     else {
690       diags.Report(clang::diag::err_drv_unsupported_option_argument)
691           << a->getOption().getName() << val;
692       return false;
693     }
694 
695     diags.Report(diagUnimplemented) << a->getOption().getName();
696     opts.setFPContractMode(fpContractMode);
697   }
698 
699   if (const llvm::opt::Arg *a =
700           args.getLastArg(clang::driver::options::OPT_menable_no_infinities)) {
701     diags.Report(diagUnimplemented) << a->getOption().getName();
702     opts.NoHonorInfs = true;
703   }
704 
705   if (const llvm::opt::Arg *a =
706           args.getLastArg(clang::driver::options::OPT_menable_no_nans)) {
707     diags.Report(diagUnimplemented) << a->getOption().getName();
708     opts.NoHonorNaNs = true;
709   }
710 
711   return true;
712 }
713 
714 bool CompilerInvocation::createFromArgs(
715     CompilerInvocation &res, llvm::ArrayRef<const char *> commandLineArgs,
716     clang::DiagnosticsEngine &diags) {
717 
718   bool success = true;
719 
720   // Set the default triple for this CompilerInvocation. This might be
721   // overridden by users with `-triple` (see the call to `ParseTargetArgs`
722   // below).
723   // NOTE: Like in Clang, it would be nice to use option marshalling
724   // for this so that the entire logic for setting-up the triple is in one
725   // place.
726   res.getTargetOpts().triple =
727       llvm::Triple::normalize(llvm::sys::getDefaultTargetTriple());
728 
729   // Parse the arguments
730   const llvm::opt::OptTable &opts = clang::driver::getDriverOptTable();
731   const unsigned includedFlagsBitmask = clang::driver::options::FC1Option;
732   unsigned missingArgIndex, missingArgCount;
733   llvm::opt::InputArgList args = opts.ParseArgs(
734       commandLineArgs, missingArgIndex, missingArgCount, includedFlagsBitmask);
735 
736   // Check for missing argument error.
737   if (missingArgCount) {
738     diags.Report(clang::diag::err_drv_missing_argument)
739         << args.getArgString(missingArgIndex) << missingArgCount;
740     success = false;
741   }
742 
743   // Issue errors on unknown arguments
744   for (const auto *a : args.filtered(clang::driver::options::OPT_UNKNOWN)) {
745     auto argString = a->getAsString(args);
746     std::string nearest;
747     if (opts.findNearest(argString, nearest, includedFlagsBitmask) > 1)
748       diags.Report(clang::diag::err_drv_unknown_argument) << argString;
749     else
750       diags.Report(clang::diag::err_drv_unknown_argument_with_suggestion)
751           << argString << nearest;
752     success = false;
753   }
754 
755   success &= parseFrontendArgs(res.getFrontendOpts(), args, diags);
756   parseTargetArgs(res.getTargetOpts(), args);
757   parsePreprocessorArgs(res.getPreprocessorOpts(), args);
758   parseCodeGenArgs(res.getCodeGenOpts(), args, diags);
759   success &= parseSemaArgs(res, args, diags);
760   success &= parseDialectArgs(res, args, diags);
761   success &= parseDiagArgs(res, args, diags);
762   res.frontendOpts.llvmArgs =
763       args.getAllArgValues(clang::driver::options::OPT_mllvm);
764 
765   res.frontendOpts.mlirArgs =
766       args.getAllArgValues(clang::driver::options::OPT_mmlir);
767 
768   success &= parseFloatingPointArgs(res, args, diags);
769 
770   return success;
771 }
772 
773 void CompilerInvocation::collectMacroDefinitions() {
774   auto &ppOpts = this->getPreprocessorOpts();
775 
776   for (unsigned i = 0, n = ppOpts.macros.size(); i != n; ++i) {
777     llvm::StringRef macro = ppOpts.macros[i].first;
778     bool isUndef = ppOpts.macros[i].second;
779 
780     std::pair<llvm::StringRef, llvm::StringRef> macroPair = macro.split('=');
781     llvm::StringRef macroName = macroPair.first;
782     llvm::StringRef macroBody = macroPair.second;
783 
784     // For an #undef'd macro, we only care about the name.
785     if (isUndef) {
786       parserOpts.predefinitions.emplace_back(macroName.str(),
787                                              std::optional<std::string>{});
788       continue;
789     }
790 
791     // For a #define'd macro, figure out the actual definition.
792     if (macroName.size() == macro.size())
793       macroBody = "1";
794     else {
795       // Note: GCC drops anything following an end-of-line character.
796       llvm::StringRef::size_type end = macroBody.find_first_of("\n\r");
797       macroBody = macroBody.substr(0, end);
798     }
799     parserOpts.predefinitions.emplace_back(
800         macroName, std::optional<std::string>(macroBody.str()));
801   }
802 }
803 
804 void CompilerInvocation::setDefaultFortranOpts() {
805   auto &fortranOptions = getFortranOpts();
806 
807   std::vector<std::string> searchDirectories{"."s};
808   fortranOptions.searchDirectories = searchDirectories;
809 
810   // Add the location of omp_lib.h to the search directories. Currently this is
811   // identical to the modules' directory.
812   fortranOptions.searchDirectories.emplace_back(getOpenMPHeadersDir());
813 
814   fortranOptions.isFixedForm = false;
815 }
816 
817 // TODO: When expanding this method, consider creating a dedicated API for
818 // this. Also at some point we will need to differentiate between different
819 // targets and add dedicated predefines for each.
820 void CompilerInvocation::setDefaultPredefinitions() {
821   auto &fortranOptions = getFortranOpts();
822   const auto &frontendOptions = getFrontendOpts();
823 
824   // Populate the macro list with version numbers and other predefinitions.
825   fortranOptions.predefinitions.emplace_back("__flang__", "1");
826   fortranOptions.predefinitions.emplace_back("__flang_major__",
827                                              FLANG_VERSION_MAJOR_STRING);
828   fortranOptions.predefinitions.emplace_back("__flang_minor__",
829                                              FLANG_VERSION_MINOR_STRING);
830   fortranOptions.predefinitions.emplace_back("__flang_patchlevel__",
831                                              FLANG_VERSION_PATCHLEVEL_STRING);
832 
833   // Add predefinitions based on extensions enabled
834   if (frontendOptions.features.IsEnabled(
835           Fortran::common::LanguageFeature::OpenACC)) {
836     fortranOptions.predefinitions.emplace_back("_OPENACC", "202011");
837   }
838   if (frontendOptions.features.IsEnabled(
839           Fortran::common::LanguageFeature::OpenMP)) {
840     fortranOptions.predefinitions.emplace_back("_OPENMP", "201511");
841   }
842   llvm::Triple targetTriple{llvm::Triple(this->targetOpts.triple)};
843   if (targetTriple.getArch() == llvm::Triple::ArchType::x86_64) {
844     fortranOptions.predefinitions.emplace_back("__x86_64__", "1");
845     fortranOptions.predefinitions.emplace_back("__x86_64", "1");
846   }
847 }
848 
849 void CompilerInvocation::setFortranOpts() {
850   auto &fortranOptions = getFortranOpts();
851   const auto &frontendOptions = getFrontendOpts();
852   const auto &preprocessorOptions = getPreprocessorOpts();
853   auto &moduleDirJ = getModuleDir();
854 
855   if (frontendOptions.fortranForm != FortranForm::Unknown) {
856     fortranOptions.isFixedForm =
857         frontendOptions.fortranForm == FortranForm::FixedForm;
858   }
859   fortranOptions.fixedFormColumns = frontendOptions.fixedFormColumns;
860 
861   fortranOptions.features = frontendOptions.features;
862   fortranOptions.encoding = frontendOptions.encoding;
863 
864   // Adding search directories specified by -I
865   fortranOptions.searchDirectories.insert(
866       fortranOptions.searchDirectories.end(),
867       preprocessorOptions.searchDirectoriesFromDashI.begin(),
868       preprocessorOptions.searchDirectoriesFromDashI.end());
869 
870   // Add the ordered list of -intrinsic-modules-path
871   fortranOptions.searchDirectories.insert(
872       fortranOptions.searchDirectories.end(),
873       preprocessorOptions.searchDirectoriesFromIntrModPath.begin(),
874       preprocessorOptions.searchDirectoriesFromIntrModPath.end());
875 
876   //  Add the default intrinsic module directory
877   fortranOptions.intrinsicModuleDirectories.emplace_back(getIntrinsicDir());
878 
879   // Add the directory supplied through -J/-module-dir to the list of search
880   // directories
881   if (moduleDirJ != ".")
882     fortranOptions.searchDirectories.emplace_back(moduleDirJ);
883 
884   if (frontendOptions.instrumentedParse)
885     fortranOptions.instrumentedParse = true;
886 
887   if (frontendOptions.showColors)
888     fortranOptions.showColors = true;
889 
890   if (frontendOptions.needProvenanceRangeToCharBlockMappings)
891     fortranOptions.needProvenanceRangeToCharBlockMappings = true;
892 
893   if (getEnableConformanceChecks()) {
894     fortranOptions.features.WarnOnAllNonstandard();
895   }
896 }
897 
898 void CompilerInvocation::setSemanticsOpts(
899     Fortran::parser::AllCookedSources &allCookedSources) {
900   auto &fortranOptions = getFortranOpts();
901 
902   semanticsContext = std::make_unique<semantics::SemanticsContext>(
903       getDefaultKinds(), fortranOptions.features, allCookedSources);
904 
905   semanticsContext->set_moduleDirectory(getModuleDir())
906       .set_searchDirectories(fortranOptions.searchDirectories)
907       .set_intrinsicModuleDirectories(fortranOptions.intrinsicModuleDirectories)
908       .set_warnOnNonstandardUsage(getEnableConformanceChecks())
909       .set_warningsAreErrors(getWarnAsErr())
910       .set_moduleFileSuffix(getModuleFileSuffix());
911 
912   llvm::Triple targetTriple{llvm::Triple(this->targetOpts.triple)};
913   // FIXME: Handle real(3) ?
914   if (targetTriple.getArch() != llvm::Triple::ArchType::x86_64) {
915     semanticsContext->targetCharacteristics().DisableType(
916         Fortran::common::TypeCategory::Real, /*kind=*/10);
917   }
918 }
919 
920 /// Set \p loweringOptions controlling lowering behavior based
921 /// on the \p optimizationLevel.
922 void CompilerInvocation::setLoweringOptions() {
923   const auto &codegenOpts = getCodeGenOpts();
924 
925   // Lower TRANSPOSE as a runtime call under -O0.
926   loweringOpts.setOptimizeTranspose(codegenOpts.OptimizationLevel > 0);
927 }
928