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