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