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 #include "flang/Frontend/CompilerInvocation.h" 10 #include "flang/Common/Fortran-features.h" 11 #include "flang/Frontend/PreprocessorOptions.h" 12 #include "flang/Semantics/semantics.h" 13 #include "flang/Version.inc" 14 #include "clang/Basic/AllDiagnostics.h" 15 #include "clang/Basic/DiagnosticDriver.h" 16 #include "clang/Basic/DiagnosticOptions.h" 17 #include "clang/Driver/DriverDiagnostic.h" 18 #include "clang/Driver/Options.h" 19 #include "llvm/ADT/StringRef.h" 20 #include "llvm/ADT/StringSwitch.h" 21 #include "llvm/Option/Arg.h" 22 #include "llvm/Option/ArgList.h" 23 #include "llvm/Option/OptTable.h" 24 #include "llvm/Support/FileSystem.h" 25 #include "llvm/Support/FileUtilities.h" 26 #include "llvm/Support/Process.h" 27 #include "llvm/Support/raw_ostream.h" 28 #include <memory> 29 30 using namespace Fortran::frontend; 31 32 //===----------------------------------------------------------------------===// 33 // Initialization. 34 //===----------------------------------------------------------------------===// 35 CompilerInvocationBase::CompilerInvocationBase() 36 : diagnosticOpts_(new clang::DiagnosticOptions()), 37 preprocessorOpts_(new PreprocessorOptions()) {} 38 39 CompilerInvocationBase::CompilerInvocationBase(const CompilerInvocationBase &x) 40 : diagnosticOpts_(new clang::DiagnosticOptions(x.GetDiagnosticOpts())), 41 preprocessorOpts_(new PreprocessorOptions(x.preprocessorOpts())) {} 42 43 CompilerInvocationBase::~CompilerInvocationBase() = default; 44 45 //===----------------------------------------------------------------------===// 46 // Deserialization (from args) 47 //===----------------------------------------------------------------------===// 48 static bool parseShowColorsArgs( 49 const llvm::opt::ArgList &args, bool defaultColor) { 50 // Color diagnostics default to auto ("on" if terminal supports) in the driver 51 // but default to off in cc1, needing an explicit OPT_fdiagnostics_color. 52 // Support both clang's -f[no-]color-diagnostics and gcc's 53 // -f[no-]diagnostics-colors[=never|always|auto]. 54 enum { 55 Colors_On, 56 Colors_Off, 57 Colors_Auto 58 } ShowColors = defaultColor ? Colors_Auto : Colors_Off; 59 60 for (auto *a : args) { 61 const llvm::opt::Option &O = a->getOption(); 62 if (O.matches(clang::driver::options::OPT_fcolor_diagnostics) || 63 O.matches(clang::driver::options::OPT_fdiagnostics_color)) { 64 ShowColors = Colors_On; 65 } else if (O.matches(clang::driver::options::OPT_fno_color_diagnostics) || 66 O.matches(clang::driver::options::OPT_fno_diagnostics_color)) { 67 ShowColors = Colors_Off; 68 } else if (O.matches(clang::driver::options::OPT_fdiagnostics_color_EQ)) { 69 llvm::StringRef value(a->getValue()); 70 if (value == "always") 71 ShowColors = Colors_On; 72 else if (value == "never") 73 ShowColors = Colors_Off; 74 else if (value == "auto") 75 ShowColors = Colors_Auto; 76 } 77 } 78 79 return ShowColors == Colors_On || 80 (ShowColors == Colors_Auto && llvm::sys::Process::StandardErrHasColors()); 81 } 82 83 bool Fortran::frontend::ParseDiagnosticArgs(clang::DiagnosticOptions &opts, 84 llvm::opt::ArgList &args, bool defaultDiagColor) { 85 opts.ShowColors = parseShowColorsArgs(args, defaultDiagColor); 86 87 return true; 88 } 89 90 // Tweak the frontend configuration based on the frontend action 91 static void setUpFrontendBasedOnAction(FrontendOptions &opts) { 92 assert(opts.programAction != Fortran::frontend::InvalidAction && 93 "Fortran frontend action not set!"); 94 95 if (opts.programAction == DebugDumpParsingLog) 96 opts.instrumentedParse = true; 97 98 if (opts.programAction == DebugDumpProvenance || 99 opts.programAction == Fortran::frontend::GetDefinition) 100 opts.needProvenanceRangeToCharBlockMappings = true; 101 } 102 103 static bool ParseFrontendArgs(FrontendOptions &opts, llvm::opt::ArgList &args, 104 clang::DiagnosticsEngine &diags) { 105 unsigned numErrorsBefore = diags.getNumErrors(); 106 107 // By default the frontend driver creates a ParseSyntaxOnly action. 108 opts.programAction = ParseSyntaxOnly; 109 110 // Identify the action (i.e. opts.ProgramAction) 111 if (const llvm::opt::Arg *a = 112 args.getLastArg(clang::driver::options::OPT_Action_Group)) { 113 switch (a->getOption().getID()) { 114 default: { 115 llvm_unreachable("Invalid option in group!"); 116 } 117 case clang::driver::options::OPT_test_io: 118 opts.programAction = InputOutputTest; 119 break; 120 case clang::driver::options::OPT_E: 121 opts.programAction = PrintPreprocessedInput; 122 break; 123 case clang::driver::options::OPT_fsyntax_only: 124 opts.programAction = ParseSyntaxOnly; 125 break; 126 case clang::driver::options::OPT_emit_obj: 127 opts.programAction = EmitObj; 128 break; 129 case clang::driver::options::OPT_fdebug_unparse: 130 opts.programAction = DebugUnparse; 131 break; 132 case clang::driver::options::OPT_fdebug_unparse_no_sema: 133 opts.programAction = DebugUnparseNoSema; 134 break; 135 case clang::driver::options::OPT_fdebug_unparse_with_symbols: 136 opts.programAction = DebugUnparseWithSymbols; 137 break; 138 case clang::driver::options::OPT_fdebug_dump_symbols: 139 opts.programAction = DebugDumpSymbols; 140 break; 141 case clang::driver::options::OPT_fdebug_dump_parse_tree: 142 opts.programAction = DebugDumpParseTree; 143 break; 144 case clang::driver::options::OPT_fdebug_dump_all: 145 opts.programAction = DebugDumpAll; 146 break; 147 case clang::driver::options::OPT_fdebug_dump_parse_tree_no_sema: 148 opts.programAction = DebugDumpParseTreeNoSema; 149 break; 150 case clang::driver::options::OPT_fdebug_dump_provenance: 151 opts.programAction = DebugDumpProvenance; 152 break; 153 case clang::driver::options::OPT_fdebug_dump_parsing_log: 154 opts.programAction = DebugDumpParsingLog; 155 break; 156 case clang::driver::options::OPT_fdebug_measure_parse_tree: 157 opts.programAction = DebugMeasureParseTree; 158 break; 159 case clang::driver::options::OPT_fdebug_pre_fir_tree: 160 opts.programAction = DebugPreFIRTree; 161 break; 162 case clang::driver::options::OPT_fget_symbols_sources: 163 opts.programAction = GetSymbolsSources; 164 break; 165 case clang::driver::options::OPT_fget_definition: 166 opts.programAction = GetDefinition; 167 break; 168 case clang::driver::options::OPT_init_only: 169 opts.programAction = InitOnly; 170 break; 171 172 // TODO: 173 // case clang::driver::options::OPT_emit_llvm: 174 // case clang::driver::options::OPT_emit_llvm_only: 175 // case clang::driver::options::OPT_emit_codegen_only: 176 // case clang::driver::options::OPT_emit_module: 177 // (...) 178 } 179 180 // Parse the values provided with `-fget-definition` (there should be 3 181 // integers) 182 if (llvm::opt::OptSpecifier(a->getOption().getID()) == 183 clang::driver::options::OPT_fget_definition) { 184 unsigned optVals[3] = {0, 0, 0}; 185 186 for (unsigned i = 0; i < 3; i++) { 187 llvm::StringRef val = a->getValue(i); 188 189 if (val.getAsInteger(10, optVals[i])) { 190 // A non-integer was encountered - that's an error. 191 diags.Report(clang::diag::err_drv_invalid_value) 192 << a->getOption().getName() << val; 193 break; 194 } 195 } 196 opts.getDefVals.line = optVals[0]; 197 opts.getDefVals.startColumn = optVals[1]; 198 opts.getDefVals.endColumn = optVals[2]; 199 } 200 } 201 202 // Parsing -load <dsopath> option and storing shared object path 203 if (llvm::opt::Arg *a = args.getLastArg(clang::driver::options::OPT_load)) { 204 opts.plugins.push_back(a->getValue()); 205 } 206 207 // Parsing -plugin <name> option and storing plugin name and setting action 208 if (const llvm::opt::Arg *a = 209 args.getLastArg(clang::driver::options::OPT_plugin)) { 210 opts.programAction = PluginAction; 211 opts.ActionName = a->getValue(); 212 } 213 214 opts.outputFile = args.getLastArgValue(clang::driver::options::OPT_o); 215 opts.showHelp = args.hasArg(clang::driver::options::OPT_help); 216 opts.showVersion = args.hasArg(clang::driver::options::OPT_version); 217 218 // Get the input kind (from the value passed via `-x`) 219 InputKind dashX(Language::Unknown); 220 if (const llvm::opt::Arg *a = 221 args.getLastArg(clang::driver::options::OPT_x)) { 222 llvm::StringRef XValue = a->getValue(); 223 // Principal languages. 224 dashX = llvm::StringSwitch<InputKind>(XValue) 225 .Case("f90", Language::Fortran) 226 .Default(Language::Unknown); 227 228 // Some special cases cannot be combined with suffixes. 229 if (dashX.IsUnknown()) 230 dashX = llvm::StringSwitch<InputKind>(XValue) 231 .Case("ir", Language::LLVM_IR) 232 .Default(Language::Unknown); 233 234 if (dashX.IsUnknown()) 235 diags.Report(clang::diag::err_drv_invalid_value) 236 << a->getAsString(args) << a->getValue(); 237 } 238 239 // Collect the input files and save them in our instance of FrontendOptions. 240 std::vector<std::string> inputs = 241 args.getAllArgValues(clang::driver::options::OPT_INPUT); 242 opts.inputs.clear(); 243 if (inputs.empty()) 244 // '-' is the default input if none is given. 245 inputs.push_back("-"); 246 for (unsigned i = 0, e = inputs.size(); i != e; ++i) { 247 InputKind ik = dashX; 248 if (ik.IsUnknown()) { 249 ik = FrontendOptions::GetInputKindForExtension( 250 llvm::StringRef(inputs[i]).rsplit('.').second); 251 if (ik.IsUnknown()) 252 ik = Language::Unknown; 253 if (i == 0) 254 dashX = ik; 255 } 256 257 opts.inputs.emplace_back(std::move(inputs[i]), ik); 258 } 259 260 // Set fortranForm based on options -ffree-form and -ffixed-form. 261 if (const auto *arg = args.getLastArg(clang::driver::options::OPT_ffixed_form, 262 clang::driver::options::OPT_ffree_form)) { 263 opts.fortranForm = 264 arg->getOption().matches(clang::driver::options::OPT_ffixed_form) 265 ? FortranForm::FixedForm 266 : FortranForm::FreeForm; 267 } 268 269 // Set fixedFormColumns based on -ffixed-line-length=<value> 270 if (const auto *arg = 271 args.getLastArg(clang::driver::options::OPT_ffixed_line_length_EQ)) { 272 llvm::StringRef argValue = llvm::StringRef(arg->getValue()); 273 std::int64_t columns = -1; 274 if (argValue == "none") { 275 columns = 0; 276 } else if (argValue.getAsInteger(/*Radix=*/10, columns)) { 277 columns = -1; 278 } 279 if (columns < 0) { 280 diags.Report(clang::diag::err_drv_negative_columns) 281 << arg->getOption().getName() << arg->getValue(); 282 } else if (columns == 0) { 283 opts.fixedFormColumns = 1000000; 284 } else if (columns < 7) { 285 diags.Report(clang::diag::err_drv_small_columns) 286 << arg->getOption().getName() << arg->getValue() << "7"; 287 } else { 288 opts.fixedFormColumns = columns; 289 } 290 } 291 292 // -f{no-}implicit-none 293 opts.features.Enable( 294 Fortran::common::LanguageFeature::ImplicitNoneTypeAlways, 295 args.hasFlag(clang::driver::options::OPT_fimplicit_none, 296 clang::driver::options::OPT_fno_implicit_none, false)); 297 298 // -f{no-}backslash 299 opts.features.Enable(Fortran::common::LanguageFeature::BackslashEscapes, 300 args.hasFlag(clang::driver::options::OPT_fbackslash, 301 clang::driver::options::OPT_fno_backslash, false)); 302 303 // -f{no-}logical-abbreviations 304 opts.features.Enable(Fortran::common::LanguageFeature::LogicalAbbreviations, 305 args.hasFlag(clang::driver::options::OPT_flogical_abbreviations, 306 clang::driver::options::OPT_fno_logical_abbreviations, false)); 307 308 // -f{no-}xor-operator 309 opts.features.Enable(Fortran::common::LanguageFeature::XOROperator, 310 args.hasFlag(clang::driver::options::OPT_fxor_operator, 311 clang::driver::options::OPT_fno_xor_operator, false)); 312 313 if (args.hasArg( 314 clang::driver::options::OPT_falternative_parameter_statement)) { 315 opts.features.Enable(Fortran::common::LanguageFeature::OldStyleParameter); 316 } 317 if (const llvm::opt::Arg *arg = 318 args.getLastArg(clang::driver::options::OPT_finput_charset_EQ)) { 319 llvm::StringRef argValue = arg->getValue(); 320 if (argValue == "utf-8") { 321 opts.encoding = Fortran::parser::Encoding::UTF_8; 322 } else if (argValue == "latin-1") { 323 opts.encoding = Fortran::parser::Encoding::LATIN_1; 324 } else { 325 diags.Report(clang::diag::err_drv_invalid_value) 326 << arg->getAsString(args) << argValue; 327 } 328 } 329 330 setUpFrontendBasedOnAction(opts); 331 opts.dashX = dashX; 332 333 return diags.getNumErrors() == numErrorsBefore; 334 } 335 336 // Generate the path to look for intrinsic modules 337 static std::string getIntrinsicDir() { 338 // TODO: Find a system independent API 339 llvm::SmallString<128> driverPath; 340 driverPath.assign(llvm::sys::fs::getMainExecutable(nullptr, nullptr)); 341 llvm::sys::path::remove_filename(driverPath); 342 driverPath.append("/../include/flang/"); 343 return std::string(driverPath); 344 } 345 346 /// Parses all preprocessor input arguments and populates the preprocessor 347 /// options accordingly. 348 /// 349 /// \param [in] opts The preprocessor options instance 350 /// \param [out] args The list of input arguments 351 static void parsePreprocessorArgs( 352 Fortran::frontend::PreprocessorOptions &opts, llvm::opt::ArgList &args) { 353 // Add macros from the command line. 354 for (const auto *currentArg : args.filtered( 355 clang::driver::options::OPT_D, clang::driver::options::OPT_U)) { 356 if (currentArg->getOption().matches(clang::driver::options::OPT_D)) { 357 opts.addMacroDef(currentArg->getValue()); 358 } else { 359 opts.addMacroUndef(currentArg->getValue()); 360 } 361 } 362 363 // Add the ordered list of -I's. 364 for (const auto *currentArg : args.filtered(clang::driver::options::OPT_I)) 365 opts.searchDirectoriesFromDashI.emplace_back(currentArg->getValue()); 366 367 // Prepend the ordered list of -intrinsic-modules-path 368 // to the default location to search. 369 for (const auto *currentArg : 370 args.filtered(clang::driver::options::OPT_fintrinsic_modules_path)) 371 opts.searchDirectoriesFromIntrModPath.emplace_back(currentArg->getValue()); 372 373 // -cpp/-nocpp 374 if (const auto *currentArg = args.getLastArg( 375 clang::driver::options::OPT_cpp, clang::driver::options::OPT_nocpp)) 376 opts.macrosFlag = 377 (currentArg->getOption().matches(clang::driver::options::OPT_cpp)) 378 ? PPMacrosFlag::Include 379 : PPMacrosFlag::Exclude; 380 381 opts.noReformat = args.hasArg(clang::driver::options::OPT_fno_reformat); 382 opts.noLineDirectives = args.hasArg(clang::driver::options::OPT_P); 383 } 384 385 /// Parses all semantic related arguments and populates the variables 386 /// options accordingly. Returns false if new errors are generated. 387 static bool parseSemaArgs(CompilerInvocation &res, llvm::opt::ArgList &args, 388 clang::DiagnosticsEngine &diags) { 389 unsigned numErrorsBefore = diags.getNumErrors(); 390 391 // -J/module-dir option 392 auto moduleDirList = 393 args.getAllArgValues(clang::driver::options::OPT_module_dir); 394 // User can only specify -J/-module-dir once 395 // https://gcc.gnu.org/onlinedocs/gfortran/Directory-Options.html 396 if (moduleDirList.size() > 1) { 397 const unsigned diagID = 398 diags.getCustomDiagID(clang::DiagnosticsEngine::Error, 399 "Only one '-module-dir/-J' option allowed"); 400 diags.Report(diagID); 401 } 402 if (moduleDirList.size() == 1) 403 res.SetModuleDir(moduleDirList[0]); 404 405 // -fdebug-module-writer option 406 if (args.hasArg(clang::driver::options::OPT_fdebug_module_writer)) { 407 res.SetDebugModuleDir(true); 408 } 409 410 // -module-suffix 411 if (const auto *moduleSuffix = 412 args.getLastArg(clang::driver::options::OPT_module_suffix)) { 413 res.SetModuleFileSuffix(moduleSuffix->getValue()); 414 } 415 416 // -f{no-}analyzed-objects-for-unparse 417 res.SetUseAnalyzedObjectsForUnparse( 418 args.hasFlag(clang::driver::options::OPT_fanalyzed_objects_for_unparse, 419 clang::driver::options::OPT_fno_analyzed_objects_for_unparse, true)); 420 421 return diags.getNumErrors() == numErrorsBefore; 422 } 423 424 /// Parses all diagnostics related arguments and populates the variables 425 /// options accordingly. Returns false if new errors are generated. 426 static bool parseDiagArgs(CompilerInvocation &res, llvm::opt::ArgList &args, 427 clang::DiagnosticsEngine &diags) { 428 unsigned numErrorsBefore = diags.getNumErrors(); 429 430 // -Werror option 431 // TODO: Currently throws a Diagnostic for anything other than -W<error>, 432 // this has to change when other -W<opt>'s are supported. 433 if (args.hasArg(clang::driver::options::OPT_W_Joined)) { 434 if (args.getLastArgValue(clang::driver::options::OPT_W_Joined) 435 .equals("error")) { 436 res.SetWarnAsErr(true); 437 } else { 438 const unsigned diagID = 439 diags.getCustomDiagID(clang::DiagnosticsEngine::Error, 440 "Only `-Werror` is supported currently."); 441 diags.Report(diagID); 442 } 443 } 444 445 return diags.getNumErrors() == numErrorsBefore; 446 } 447 448 /// Parses all Dialect related arguments and populates the variables 449 /// options accordingly. Returns false if new errors are generated. 450 static bool parseDialectArgs(CompilerInvocation &res, llvm::opt::ArgList &args, 451 clang::DiagnosticsEngine &diags) { 452 unsigned numErrorsBefore = diags.getNumErrors(); 453 454 // -fdefault* family 455 if (args.hasArg(clang::driver::options::OPT_fdefault_real_8)) { 456 res.defaultKinds().set_defaultRealKind(8); 457 res.defaultKinds().set_doublePrecisionKind(16); 458 } 459 if (args.hasArg(clang::driver::options::OPT_fdefault_integer_8)) { 460 res.defaultKinds().set_defaultIntegerKind(8); 461 res.defaultKinds().set_subscriptIntegerKind(8); 462 res.defaultKinds().set_sizeIntegerKind(8); 463 } 464 if (args.hasArg(clang::driver::options::OPT_fdefault_double_8)) { 465 if (!args.hasArg(clang::driver::options::OPT_fdefault_real_8)) { 466 // -fdefault-double-8 has to be used with -fdefault-real-8 467 // to be compatible with gfortran 468 const unsigned diagID = 469 diags.getCustomDiagID(clang::DiagnosticsEngine::Error, 470 "Use of `-fdefault-double-8` requires `-fdefault-real-8`"); 471 diags.Report(diagID); 472 } 473 // https://gcc.gnu.org/onlinedocs/gfortran/Fortran-Dialect-Options.html 474 res.defaultKinds().set_doublePrecisionKind(8); 475 } 476 if (args.hasArg(clang::driver::options::OPT_flarge_sizes)) 477 res.defaultKinds().set_sizeIntegerKind(8); 478 479 // -fopenmp and -fopenacc 480 if (args.hasArg(clang::driver::options::OPT_fopenacc)) { 481 res.frontendOpts().features.Enable( 482 Fortran::common::LanguageFeature::OpenACC); 483 } 484 if (args.hasArg(clang::driver::options::OPT_fopenmp)) { 485 res.frontendOpts().features.Enable( 486 Fortran::common::LanguageFeature::OpenMP); 487 } 488 489 // -pedantic 490 if (args.hasArg(clang::driver::options::OPT_pedantic)) { 491 res.set_EnableConformanceChecks(); 492 } 493 // -std=f2018 (currently this implies -pedantic) 494 // TODO: Set proper options when more fortran standards 495 // are supported. 496 if (args.hasArg(clang::driver::options::OPT_std_EQ)) { 497 auto standard = args.getLastArgValue(clang::driver::options::OPT_std_EQ); 498 // We only allow f2018 as the given standard 499 if (standard.equals("f2018")) { 500 res.set_EnableConformanceChecks(); 501 } else { 502 const unsigned diagID = 503 diags.getCustomDiagID(clang::DiagnosticsEngine::Error, 504 "Only -std=f2018 is allowed currently."); 505 diags.Report(diagID); 506 } 507 } 508 return diags.getNumErrors() == numErrorsBefore; 509 } 510 511 bool CompilerInvocation::CreateFromArgs(CompilerInvocation &res, 512 llvm::ArrayRef<const char *> commandLineArgs, 513 clang::DiagnosticsEngine &diags) { 514 515 bool success = true; 516 517 // Parse the arguments 518 const llvm::opt::OptTable &opts = clang::driver::getDriverOptTable(); 519 const unsigned includedFlagsBitmask = clang::driver::options::FC1Option; 520 unsigned missingArgIndex, missingArgCount; 521 llvm::opt::InputArgList args = opts.ParseArgs( 522 commandLineArgs, missingArgIndex, missingArgCount, includedFlagsBitmask); 523 524 // Check for missing argument error. 525 if (missingArgCount) { 526 diags.Report(clang::diag::err_drv_missing_argument) 527 << args.getArgString(missingArgIndex) << missingArgCount; 528 success = false; 529 } 530 531 // Issue errors on unknown arguments 532 for (const auto *a : args.filtered(clang::driver::options::OPT_UNKNOWN)) { 533 auto argString = a->getAsString(args); 534 std::string nearest; 535 if (opts.findNearest(argString, nearest, includedFlagsBitmask) > 1) 536 diags.Report(clang::diag::err_drv_unknown_argument) << argString; 537 else 538 diags.Report(clang::diag::err_drv_unknown_argument_with_suggestion) 539 << argString << nearest; 540 success = false; 541 } 542 543 success &= ParseFrontendArgs(res.frontendOpts(), args, diags); 544 parsePreprocessorArgs(res.preprocessorOpts(), args); 545 success &= parseSemaArgs(res, args, diags); 546 success &= parseDialectArgs(res, args, diags); 547 success &= parseDiagArgs(res, args, diags); 548 549 return success; 550 } 551 552 void CompilerInvocation::collectMacroDefinitions() { 553 auto &ppOpts = this->preprocessorOpts(); 554 555 for (unsigned i = 0, n = ppOpts.macros.size(); i != n; ++i) { 556 llvm::StringRef macro = ppOpts.macros[i].first; 557 bool isUndef = ppOpts.macros[i].second; 558 559 std::pair<llvm::StringRef, llvm::StringRef> macroPair = macro.split('='); 560 llvm::StringRef macroName = macroPair.first; 561 llvm::StringRef macroBody = macroPair.second; 562 563 // For an #undef'd macro, we only care about the name. 564 if (isUndef) { 565 parserOpts_.predefinitions.emplace_back( 566 macroName.str(), std::optional<std::string>{}); 567 continue; 568 } 569 570 // For a #define'd macro, figure out the actual definition. 571 if (macroName.size() == macro.size()) 572 macroBody = "1"; 573 else { 574 // Note: GCC drops anything following an end-of-line character. 575 llvm::StringRef::size_type End = macroBody.find_first_of("\n\r"); 576 macroBody = macroBody.substr(0, End); 577 } 578 parserOpts_.predefinitions.emplace_back( 579 macroName, std::optional<std::string>(macroBody.str())); 580 } 581 } 582 583 void CompilerInvocation::SetDefaultFortranOpts() { 584 auto &fortranOptions = fortranOpts(); 585 586 std::vector<std::string> searchDirectories{"."s}; 587 fortranOptions.searchDirectories = searchDirectories; 588 fortranOptions.isFixedForm = false; 589 } 590 591 // TODO: When expanding this method, consider creating a dedicated API for 592 // this. Also at some point we will need to differentiate between different 593 // targets and add dedicated predefines for each. 594 void CompilerInvocation::setDefaultPredefinitions() { 595 auto &fortranOptions = fortranOpts(); 596 const auto &frontendOptions = frontendOpts(); 597 598 // Populate the macro list with version numbers and other predefinitions. 599 fortranOptions.predefinitions.emplace_back("__flang__", "1"); 600 fortranOptions.predefinitions.emplace_back( 601 "__flang_major__", FLANG_VERSION_MAJOR_STRING); 602 fortranOptions.predefinitions.emplace_back( 603 "__flang_minor__", FLANG_VERSION_MINOR_STRING); 604 fortranOptions.predefinitions.emplace_back( 605 "__flang_patchlevel__", FLANG_VERSION_PATCHLEVEL_STRING); 606 607 // Add predefinitions based on extensions enabled 608 if (frontendOptions.features.IsEnabled( 609 Fortran::common::LanguageFeature::OpenACC)) { 610 fortranOptions.predefinitions.emplace_back("_OPENACC", "202011"); 611 } 612 if (frontendOptions.features.IsEnabled( 613 Fortran::common::LanguageFeature::OpenMP)) { 614 fortranOptions.predefinitions.emplace_back("_OPENMP", "201511"); 615 } 616 } 617 618 void CompilerInvocation::setFortranOpts() { 619 auto &fortranOptions = fortranOpts(); 620 const auto &frontendOptions = frontendOpts(); 621 const auto &preprocessorOptions = preprocessorOpts(); 622 auto &moduleDirJ = moduleDir(); 623 624 if (frontendOptions.fortranForm != FortranForm::Unknown) { 625 fortranOptions.isFixedForm = 626 frontendOptions.fortranForm == FortranForm::FixedForm; 627 } 628 fortranOptions.fixedFormColumns = frontendOptions.fixedFormColumns; 629 630 fortranOptions.features = frontendOptions.features; 631 fortranOptions.encoding = frontendOptions.encoding; 632 633 // Adding search directories specified by -I 634 fortranOptions.searchDirectories.insert( 635 fortranOptions.searchDirectories.end(), 636 preprocessorOptions.searchDirectoriesFromDashI.begin(), 637 preprocessorOptions.searchDirectoriesFromDashI.end()); 638 639 // Add the ordered list of -intrinsic-modules-path 640 fortranOptions.searchDirectories.insert( 641 fortranOptions.searchDirectories.end(), 642 preprocessorOptions.searchDirectoriesFromIntrModPath.begin(), 643 preprocessorOptions.searchDirectoriesFromIntrModPath.end()); 644 645 // Add the default intrinsic module directory at the end 646 fortranOptions.searchDirectories.emplace_back(getIntrinsicDir()); 647 648 // Add the directory supplied through -J/-module-dir to the list of search 649 // directories 650 if (moduleDirJ.compare(".") != 0) 651 fortranOptions.searchDirectories.emplace_back(moduleDirJ); 652 653 if (frontendOptions.instrumentedParse) 654 fortranOptions.instrumentedParse = true; 655 656 if (frontendOptions.needProvenanceRangeToCharBlockMappings) 657 fortranOptions.needProvenanceRangeToCharBlockMappings = true; 658 659 if (enableConformanceChecks()) { 660 fortranOptions.features.WarnOnAllNonstandard(); 661 } 662 } 663 664 void CompilerInvocation::setSemanticsOpts( 665 Fortran::parser::AllCookedSources &allCookedSources) { 666 const auto &fortranOptions = fortranOpts(); 667 668 semanticsContext_ = std::make_unique<semantics::SemanticsContext>( 669 defaultKinds(), fortranOptions.features, allCookedSources); 670 671 semanticsContext_->set_moduleDirectory(moduleDir()) 672 .set_searchDirectories(fortranOptions.searchDirectories) 673 .set_warnOnNonstandardUsage(enableConformanceChecks()) 674 .set_warningsAreErrors(warnAsErr()) 675 .set_moduleFileSuffix(moduleFileSuffix()); 676 } 677