xref: /llvm-project/flang/lib/Frontend/CompilerInvocation.cpp (revision a784de783af5096e593c5e214c2c78215fe303f5)
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 = args.getLastArg(clang::driver::options::OPT_ffixed_form,
383           clang::driver::options::OPT_ffree_form)) {
384     opts.fortranForm =
385         arg->getOption().matches(clang::driver::options::OPT_ffixed_form)
386         ? FortranForm::FixedForm
387         : FortranForm::FreeForm;
388   }
389 
390   // Set fixedFormColumns based on -ffixed-line-length=<value>
391   if (const auto *arg =
392           args.getLastArg(clang::driver::options::OPT_ffixed_line_length_EQ)) {
393     llvm::StringRef argValue = llvm::StringRef(arg->getValue());
394     std::int64_t columns = -1;
395     if (argValue == "none") {
396       columns = 0;
397     } else if (argValue.getAsInteger(/*Radix=*/10, columns)) {
398       columns = -1;
399     }
400     if (columns < 0) {
401       diags.Report(clang::diag::err_drv_negative_columns)
402           << arg->getOption().getName() << arg->getValue();
403     } else if (columns == 0) {
404       opts.fixedFormColumns = 1000000;
405     } else if (columns < 7) {
406       diags.Report(clang::diag::err_drv_small_columns)
407           << arg->getOption().getName() << arg->getValue() << "7";
408     } else {
409       opts.fixedFormColumns = columns;
410     }
411   }
412 
413   // Set conversion based on -fconvert=<value>
414   if (const auto *arg =
415           args.getLastArg(clang::driver::options::OPT_fconvert_EQ)) {
416     const char *argValue = arg->getValue();
417     if (auto convert = parseConvertArg(argValue))
418       opts.envDefaults.push_back({"FORT_CONVERT", *convert});
419     else
420       diags.Report(clang::diag::err_drv_invalid_value)
421           << arg->getAsString(args) << argValue;
422   }
423 
424   // -f{no-}implicit-none
425   opts.features.Enable(
426       Fortran::common::LanguageFeature::ImplicitNoneTypeAlways,
427       args.hasFlag(clang::driver::options::OPT_fimplicit_none,
428           clang::driver::options::OPT_fno_implicit_none, false));
429 
430   // -f{no-}backslash
431   opts.features.Enable(Fortran::common::LanguageFeature::BackslashEscapes,
432       args.hasFlag(clang::driver::options::OPT_fbackslash,
433           clang::driver::options::OPT_fno_backslash, false));
434 
435   // -f{no-}logical-abbreviations
436   opts.features.Enable(Fortran::common::LanguageFeature::LogicalAbbreviations,
437       args.hasFlag(clang::driver::options::OPT_flogical_abbreviations,
438           clang::driver::options::OPT_fno_logical_abbreviations, false));
439 
440   // -f{no-}xor-operator
441   opts.features.Enable(Fortran::common::LanguageFeature::XOROperator,
442       args.hasFlag(clang::driver::options::OPT_fxor_operator,
443           clang::driver::options::OPT_fno_xor_operator, false));
444 
445   // -fno-automatic
446   if (args.hasArg(clang::driver::options::OPT_fno_automatic)) {
447     opts.features.Enable(Fortran::common::LanguageFeature::DefaultSave);
448   }
449 
450   if (args.hasArg(
451           clang::driver::options::OPT_falternative_parameter_statement)) {
452     opts.features.Enable(Fortran::common::LanguageFeature::OldStyleParameter);
453   }
454   if (const llvm::opt::Arg *arg =
455           args.getLastArg(clang::driver::options::OPT_finput_charset_EQ)) {
456     llvm::StringRef argValue = arg->getValue();
457     if (argValue == "utf-8") {
458       opts.encoding = Fortran::parser::Encoding::UTF_8;
459     } else if (argValue == "latin-1") {
460       opts.encoding = Fortran::parser::Encoding::LATIN_1;
461     } else {
462       diags.Report(clang::diag::err_drv_invalid_value)
463           << arg->getAsString(args) << argValue;
464     }
465   }
466 
467   setUpFrontendBasedOnAction(opts);
468   opts.dashX = dashX;
469 
470   return diags.getNumErrors() == numErrorsBefore;
471 }
472 
473 // Generate the path to look for intrinsic modules
474 static std::string getIntrinsicDir() {
475   // TODO: Find a system independent API
476   llvm::SmallString<128> driverPath;
477   driverPath.assign(llvm::sys::fs::getMainExecutable(nullptr, nullptr));
478   llvm::sys::path::remove_filename(driverPath);
479   driverPath.append("/../include/flang/");
480   return std::string(driverPath);
481 }
482 
483 // Generate the path to look for OpenMP headers
484 static std::string getOpenMPHeadersDir() {
485   llvm::SmallString<128> includePath;
486   includePath.assign(llvm::sys::fs::getMainExecutable(nullptr, nullptr));
487   llvm::sys::path::remove_filename(includePath);
488   includePath.append("/../include/flang/OpenMP/");
489   return std::string(includePath);
490 }
491 
492 /// Parses all preprocessor input arguments and populates the preprocessor
493 /// options accordingly.
494 ///
495 /// \param [in] opts The preprocessor options instance
496 /// \param [out] args The list of input arguments
497 static void parsePreprocessorArgs(
498     Fortran::frontend::PreprocessorOptions &opts, llvm::opt::ArgList &args) {
499   // Add macros from the command line.
500   for (const auto *currentArg : args.filtered(
501            clang::driver::options::OPT_D, clang::driver::options::OPT_U)) {
502     if (currentArg->getOption().matches(clang::driver::options::OPT_D)) {
503       opts.addMacroDef(currentArg->getValue());
504     } else {
505       opts.addMacroUndef(currentArg->getValue());
506     }
507   }
508 
509   // Add the ordered list of -I's.
510   for (const auto *currentArg : args.filtered(clang::driver::options::OPT_I))
511     opts.searchDirectoriesFromDashI.emplace_back(currentArg->getValue());
512 
513   // Prepend the ordered list of -intrinsic-modules-path
514   // to the default location to search.
515   for (const auto *currentArg :
516       args.filtered(clang::driver::options::OPT_fintrinsic_modules_path))
517     opts.searchDirectoriesFromIntrModPath.emplace_back(currentArg->getValue());
518 
519   // -cpp/-nocpp
520   if (const auto *currentArg = args.getLastArg(
521           clang::driver::options::OPT_cpp, clang::driver::options::OPT_nocpp))
522     opts.macrosFlag =
523         (currentArg->getOption().matches(clang::driver::options::OPT_cpp))
524         ? PPMacrosFlag::Include
525         : PPMacrosFlag::Exclude;
526 
527   opts.noReformat = args.hasArg(clang::driver::options::OPT_fno_reformat);
528   opts.noLineDirectives = args.hasArg(clang::driver::options::OPT_P);
529 }
530 
531 /// Parses all semantic related arguments and populates the variables
532 /// options accordingly. Returns false if new errors are generated.
533 static bool parseSemaArgs(CompilerInvocation &res, llvm::opt::ArgList &args,
534     clang::DiagnosticsEngine &diags) {
535   unsigned numErrorsBefore = diags.getNumErrors();
536 
537   // -J/module-dir option
538   auto moduleDirList =
539       args.getAllArgValues(clang::driver::options::OPT_module_dir);
540   // User can only specify -J/-module-dir once
541   // https://gcc.gnu.org/onlinedocs/gfortran/Directory-Options.html
542   if (moduleDirList.size() > 1) {
543     const unsigned diagID =
544         diags.getCustomDiagID(clang::DiagnosticsEngine::Error,
545             "Only one '-module-dir/-J' option allowed");
546     diags.Report(diagID);
547   }
548   if (moduleDirList.size() == 1)
549     res.setModuleDir(moduleDirList[0]);
550 
551   // -fdebug-module-writer option
552   if (args.hasArg(clang::driver::options::OPT_fdebug_module_writer)) {
553     res.setDebugModuleDir(true);
554   }
555 
556   // -module-suffix
557   if (const auto *moduleSuffix =
558           args.getLastArg(clang::driver::options::OPT_module_suffix)) {
559     res.setModuleFileSuffix(moduleSuffix->getValue());
560   }
561 
562   // -f{no-}analyzed-objects-for-unparse
563   res.setUseAnalyzedObjectsForUnparse(args.hasFlag(
564       clang::driver::options::OPT_fanalyzed_objects_for_unparse,
565       clang::driver::options::OPT_fno_analyzed_objects_for_unparse, true));
566 
567   return diags.getNumErrors() == numErrorsBefore;
568 }
569 
570 /// Parses all diagnostics related arguments and populates the variables
571 /// options accordingly. Returns false if new errors are generated.
572 static bool parseDiagArgs(CompilerInvocation &res, llvm::opt::ArgList &args,
573     clang::DiagnosticsEngine &diags) {
574   unsigned numErrorsBefore = diags.getNumErrors();
575 
576   // -Werror option
577   // TODO: Currently throws a Diagnostic for anything other than -W<error>,
578   // this has to change when other -W<opt>'s are supported.
579   if (args.hasArg(clang::driver::options::OPT_W_Joined)) {
580     if (args.getLastArgValue(clang::driver::options::OPT_W_Joined)
581             .equals("error")) {
582       res.setWarnAsErr(true);
583     } else {
584       const unsigned diagID =
585           diags.getCustomDiagID(clang::DiagnosticsEngine::Error,
586               "Only `-Werror` is supported currently.");
587       diags.Report(diagID);
588     }
589   }
590 
591   // Default to off for `flang-new -fc1`.
592   res.getFrontendOpts().showColors =
593       parseShowColorsArgs(args, /*defaultDiagColor=*/false);
594 
595   return diags.getNumErrors() == numErrorsBefore;
596 }
597 
598 /// Parses all Dialect related arguments and populates the variables
599 /// options accordingly. Returns false if new errors are generated.
600 static bool parseDialectArgs(CompilerInvocation &res, llvm::opt::ArgList &args,
601     clang::DiagnosticsEngine &diags) {
602   unsigned numErrorsBefore = diags.getNumErrors();
603 
604   // -fdefault* family
605   if (args.hasArg(clang::driver::options::OPT_fdefault_real_8)) {
606     res.getDefaultKinds().set_defaultRealKind(8);
607     res.getDefaultKinds().set_doublePrecisionKind(16);
608   }
609   if (args.hasArg(clang::driver::options::OPT_fdefault_integer_8)) {
610     res.getDefaultKinds().set_defaultIntegerKind(8);
611     res.getDefaultKinds().set_subscriptIntegerKind(8);
612     res.getDefaultKinds().set_sizeIntegerKind(8);
613   }
614   if (args.hasArg(clang::driver::options::OPT_fdefault_double_8)) {
615     if (!args.hasArg(clang::driver::options::OPT_fdefault_real_8)) {
616       // -fdefault-double-8 has to be used with -fdefault-real-8
617       // to be compatible with gfortran
618       const unsigned diagID =
619           diags.getCustomDiagID(clang::DiagnosticsEngine::Error,
620               "Use of `-fdefault-double-8` requires `-fdefault-real-8`");
621       diags.Report(diagID);
622     }
623     // https://gcc.gnu.org/onlinedocs/gfortran/Fortran-Dialect-Options.html
624     res.getDefaultKinds().set_doublePrecisionKind(8);
625   }
626   if (args.hasArg(clang::driver::options::OPT_flarge_sizes))
627     res.getDefaultKinds().set_sizeIntegerKind(8);
628 
629   // -fopenmp and -fopenacc
630   if (args.hasArg(clang::driver::options::OPT_fopenacc)) {
631     res.getFrontendOpts().features.Enable(
632         Fortran::common::LanguageFeature::OpenACC);
633   }
634   if (args.hasArg(clang::driver::options::OPT_fopenmp)) {
635     res.getFrontendOpts().features.Enable(
636         Fortran::common::LanguageFeature::OpenMP);
637   }
638 
639   // -pedantic
640   if (args.hasArg(clang::driver::options::OPT_pedantic)) {
641     res.setEnableConformanceChecks();
642   }
643   // -std=f2018 (currently this implies -pedantic)
644   // TODO: Set proper options when more fortran standards
645   // are supported.
646   if (args.hasArg(clang::driver::options::OPT_std_EQ)) {
647     auto standard = args.getLastArgValue(clang::driver::options::OPT_std_EQ);
648     // We only allow f2018 as the given standard
649     if (standard.equals("f2018")) {
650       res.setEnableConformanceChecks();
651     } else {
652       const unsigned diagID =
653           diags.getCustomDiagID(clang::DiagnosticsEngine::Error,
654               "Only -std=f2018 is allowed currently.");
655       diags.Report(diagID);
656     }
657   }
658   return diags.getNumErrors() == numErrorsBefore;
659 }
660 
661 /// Parses all floating point related arguments and populates the
662 /// CompilerInvocation accordingly.
663 /// Returns false if new errors are generated.
664 ///
665 /// \param [out] invoc Stores the processed arguments
666 /// \param [in] args The compiler invocation arguments to parse
667 /// \param [out] diags DiagnosticsEngine to report erros with
668 static bool parseFloatingPointArgs(CompilerInvocation &invoc,
669                                    llvm::opt::ArgList &args,
670                                    clang::DiagnosticsEngine &diags) {
671   LangOptions &opts = invoc.getLangOpts();
672   const unsigned diagUnimplemented = diags.getCustomDiagID(
673       clang::DiagnosticsEngine::Warning, "%0 is not currently implemented");
674 
675   if (const llvm::opt::Arg *a =
676           args.getLastArg(clang::driver::options::OPT_ffp_contract)) {
677     const llvm::StringRef val = a->getValue();
678     enum LangOptions::FPModeKind fpContractMode;
679 
680     if (val == "off")
681       fpContractMode = LangOptions::FPM_Off;
682     else if (val == "fast")
683       fpContractMode = LangOptions::FPM_Fast;
684     else {
685       diags.Report(clang::diag::err_drv_unsupported_option_argument)
686           << a->getOption().getName() << val;
687       return false;
688     }
689 
690     diags.Report(diagUnimplemented) << a->getOption().getName();
691     opts.setFPContractMode(fpContractMode);
692   }
693 
694   return true;
695 }
696 
697 bool CompilerInvocation::createFromArgs(
698     CompilerInvocation &res, llvm::ArrayRef<const char *> commandLineArgs,
699     clang::DiagnosticsEngine &diags) {
700 
701   bool success = true;
702 
703   // Set the default triple for this CompilerInvocation. This might be
704   // overridden by users with `-triple` (see the call to `ParseTargetArgs`
705   // below).
706   // NOTE: Like in Clang, it would be nice to use option marshalling
707   // for this so that the entire logic for setting-up the triple is in one
708   // place.
709   res.getTargetOpts().triple =
710       llvm::Triple::normalize(llvm::sys::getDefaultTargetTriple());
711 
712   // Parse the arguments
713   const llvm::opt::OptTable &opts = clang::driver::getDriverOptTable();
714   const unsigned includedFlagsBitmask = clang::driver::options::FC1Option;
715   unsigned missingArgIndex, missingArgCount;
716   llvm::opt::InputArgList args = opts.ParseArgs(
717       commandLineArgs, missingArgIndex, missingArgCount, includedFlagsBitmask);
718 
719   // Check for missing argument error.
720   if (missingArgCount) {
721     diags.Report(clang::diag::err_drv_missing_argument)
722         << args.getArgString(missingArgIndex) << missingArgCount;
723     success = false;
724   }
725 
726   // Issue errors on unknown arguments
727   for (const auto *a : args.filtered(clang::driver::options::OPT_UNKNOWN)) {
728     auto argString = a->getAsString(args);
729     std::string nearest;
730     if (opts.findNearest(argString, nearest, includedFlagsBitmask) > 1)
731       diags.Report(clang::diag::err_drv_unknown_argument) << argString;
732     else
733       diags.Report(clang::diag::err_drv_unknown_argument_with_suggestion)
734           << argString << nearest;
735     success = false;
736   }
737 
738   success &= parseFrontendArgs(res.getFrontendOpts(), args, diags);
739   parseTargetArgs(res.getTargetOpts(), args);
740   parsePreprocessorArgs(res.getPreprocessorOpts(), args);
741   parseCodeGenArgs(res.getCodeGenOpts(), args, diags);
742   success &= parseSemaArgs(res, args, diags);
743   success &= parseDialectArgs(res, args, diags);
744   success &= parseDiagArgs(res, args, diags);
745   res.frontendOpts.llvmArgs =
746       args.getAllArgValues(clang::driver::options::OPT_mllvm);
747 
748   res.frontendOpts.mlirArgs =
749       args.getAllArgValues(clang::driver::options::OPT_mmlir);
750 
751   success &= parseFloatingPointArgs(res, args, diags);
752 
753   return success;
754 }
755 
756 void CompilerInvocation::collectMacroDefinitions() {
757   auto &ppOpts = this->getPreprocessorOpts();
758 
759   for (unsigned i = 0, n = ppOpts.macros.size(); i != n; ++i) {
760     llvm::StringRef macro = ppOpts.macros[i].first;
761     bool isUndef = ppOpts.macros[i].second;
762 
763     std::pair<llvm::StringRef, llvm::StringRef> macroPair = macro.split('=');
764     llvm::StringRef macroName = macroPair.first;
765     llvm::StringRef macroBody = macroPair.second;
766 
767     // For an #undef'd macro, we only care about the name.
768     if (isUndef) {
769       parserOpts.predefinitions.emplace_back(macroName.str(),
770                                              std::optional<std::string>{});
771       continue;
772     }
773 
774     // For a #define'd macro, figure out the actual definition.
775     if (macroName.size() == macro.size())
776       macroBody = "1";
777     else {
778       // Note: GCC drops anything following an end-of-line character.
779       llvm::StringRef::size_type end = macroBody.find_first_of("\n\r");
780       macroBody = macroBody.substr(0, end);
781     }
782     parserOpts.predefinitions.emplace_back(
783         macroName, std::optional<std::string>(macroBody.str()));
784   }
785 }
786 
787 void CompilerInvocation::setDefaultFortranOpts() {
788   auto &fortranOptions = getFortranOpts();
789 
790   std::vector<std::string> searchDirectories{"."s};
791   fortranOptions.searchDirectories = searchDirectories;
792 
793   // Add the location of omp_lib.h to the search directories. Currently this is
794   // identical to the modules' directory.
795   fortranOptions.searchDirectories.emplace_back(getOpenMPHeadersDir());
796 
797   fortranOptions.isFixedForm = false;
798 }
799 
800 // TODO: When expanding this method, consider creating a dedicated API for
801 // this. Also at some point we will need to differentiate between different
802 // targets and add dedicated predefines for each.
803 void CompilerInvocation::setDefaultPredefinitions() {
804   auto &fortranOptions = getFortranOpts();
805   const auto &frontendOptions = getFrontendOpts();
806 
807   // Populate the macro list with version numbers and other predefinitions.
808   fortranOptions.predefinitions.emplace_back("__flang__", "1");
809   fortranOptions.predefinitions.emplace_back(
810       "__flang_major__", FLANG_VERSION_MAJOR_STRING);
811   fortranOptions.predefinitions.emplace_back(
812       "__flang_minor__", FLANG_VERSION_MINOR_STRING);
813   fortranOptions.predefinitions.emplace_back(
814       "__flang_patchlevel__", FLANG_VERSION_PATCHLEVEL_STRING);
815 
816   // Add predefinitions based on extensions enabled
817   if (frontendOptions.features.IsEnabled(
818           Fortran::common::LanguageFeature::OpenACC)) {
819     fortranOptions.predefinitions.emplace_back("_OPENACC", "202011");
820   }
821   if (frontendOptions.features.IsEnabled(
822           Fortran::common::LanguageFeature::OpenMP)) {
823     fortranOptions.predefinitions.emplace_back("_OPENMP", "201511");
824   }
825   llvm::Triple targetTriple{llvm::Triple(this->targetOpts.triple)};
826   if (targetTriple.getArch() == llvm::Triple::ArchType::x86_64) {
827     fortranOptions.predefinitions.emplace_back("__x86_64__", "1");
828     fortranOptions.predefinitions.emplace_back("__x86_64", "1");
829   }
830 }
831 
832 void CompilerInvocation::setFortranOpts() {
833   auto &fortranOptions = getFortranOpts();
834   const auto &frontendOptions = getFrontendOpts();
835   const auto &preprocessorOptions = getPreprocessorOpts();
836   auto &moduleDirJ = getModuleDir();
837 
838   if (frontendOptions.fortranForm != FortranForm::Unknown) {
839     fortranOptions.isFixedForm =
840         frontendOptions.fortranForm == FortranForm::FixedForm;
841   }
842   fortranOptions.fixedFormColumns = frontendOptions.fixedFormColumns;
843 
844   fortranOptions.features = frontendOptions.features;
845   fortranOptions.encoding = frontendOptions.encoding;
846 
847   // Adding search directories specified by -I
848   fortranOptions.searchDirectories.insert(
849       fortranOptions.searchDirectories.end(),
850       preprocessorOptions.searchDirectoriesFromDashI.begin(),
851       preprocessorOptions.searchDirectoriesFromDashI.end());
852 
853   // Add the ordered list of -intrinsic-modules-path
854   fortranOptions.searchDirectories.insert(
855       fortranOptions.searchDirectories.end(),
856       preprocessorOptions.searchDirectoriesFromIntrModPath.begin(),
857       preprocessorOptions.searchDirectoriesFromIntrModPath.end());
858 
859   //  Add the default intrinsic module directory
860   fortranOptions.intrinsicModuleDirectories.emplace_back(getIntrinsicDir());
861 
862   // Add the directory supplied through -J/-module-dir to the list of search
863   // directories
864   if (moduleDirJ != ".")
865     fortranOptions.searchDirectories.emplace_back(moduleDirJ);
866 
867   if (frontendOptions.instrumentedParse)
868     fortranOptions.instrumentedParse = true;
869 
870   if (frontendOptions.showColors)
871     fortranOptions.showColors = true;
872 
873   if (frontendOptions.needProvenanceRangeToCharBlockMappings)
874     fortranOptions.needProvenanceRangeToCharBlockMappings = true;
875 
876   if (getEnableConformanceChecks()) {
877     fortranOptions.features.WarnOnAllNonstandard();
878   }
879 }
880 
881 void CompilerInvocation::setSemanticsOpts(
882     Fortran::parser::AllCookedSources &allCookedSources) {
883   auto &fortranOptions = getFortranOpts();
884 
885   semanticsContext = std::make_unique<semantics::SemanticsContext>(
886       getDefaultKinds(), fortranOptions.features, allCookedSources);
887 
888   semanticsContext->set_moduleDirectory(getModuleDir())
889       .set_searchDirectories(fortranOptions.searchDirectories)
890       .set_intrinsicModuleDirectories(fortranOptions.intrinsicModuleDirectories)
891       .set_warnOnNonstandardUsage(getEnableConformanceChecks())
892       .set_warningsAreErrors(getWarnAsErr())
893       .set_moduleFileSuffix(getModuleFileSuffix());
894 
895   llvm::Triple targetTriple{llvm::Triple(this->targetOpts.triple)};
896   // FIXME: Handle real(3) ?
897   if (targetTriple.getArch() != llvm::Triple::ArchType::x86_64) {
898     semanticsContext->targetCharacteristics().DisableType(
899         Fortran::common::TypeCategory::Real, /*kind=*/10);
900   }
901 }
902 
903 /// Set \p loweringOptions controlling lowering behavior based
904 /// on the \p optimizationLevel.
905 void CompilerInvocation::setLoweringOptions() {
906   const auto &codegenOpts = getCodeGenOpts();
907 
908   // Lower TRANSPOSE as a runtime call under -O0.
909   loweringOpts.setOptimizeTranspose(codegenOpts.OptimizationLevel > 0);
910 }
911