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 638 // Get the input kind (from the value passed via `-x`) 639 InputKind dashX(Language::Unknown); 640 if (const llvm::opt::Arg *a = 641 args.getLastArg(clang::driver::options::OPT_x)) { 642 llvm::StringRef xValue = a->getValue(); 643 // Principal languages. 644 dashX = llvm::StringSwitch<InputKind>(xValue) 645 // Flang does not differentiate between pre-processed and not 646 // pre-processed inputs. 647 .Case("f95", Language::Fortran) 648 .Case("f95-cpp-input", Language::Fortran) 649 // CUDA Fortran 650 .Case("cuda", Language::Fortran) 651 .Default(Language::Unknown); 652 653 // Flang's intermediate representations. 654 if (dashX.isUnknown()) 655 dashX = llvm::StringSwitch<InputKind>(xValue) 656 .Case("ir", Language::LLVM_IR) 657 .Case("fir", Language::MLIR) 658 .Case("mlir", Language::MLIR) 659 .Default(Language::Unknown); 660 661 if (dashX.isUnknown()) 662 diags.Report(clang::diag::err_drv_invalid_value) 663 << a->getAsString(args) << a->getValue(); 664 } 665 666 // Collect the input files and save them in our instance of FrontendOptions. 667 std::vector<std::string> inputs = 668 args.getAllArgValues(clang::driver::options::OPT_INPUT); 669 opts.inputs.clear(); 670 if (inputs.empty()) 671 // '-' is the default input if none is given. 672 inputs.push_back("-"); 673 for (unsigned i = 0, e = inputs.size(); i != e; ++i) { 674 InputKind ik = dashX; 675 if (ik.isUnknown()) { 676 ik = FrontendOptions::getInputKindForExtension( 677 llvm::StringRef(inputs[i]).rsplit('.').second); 678 if (ik.isUnknown()) 679 ik = Language::Unknown; 680 if (i == 0) 681 dashX = ik; 682 } 683 684 opts.inputs.emplace_back(std::move(inputs[i]), ik); 685 } 686 687 // Set fortranForm based on options -ffree-form and -ffixed-form. 688 if (const auto *arg = 689 args.getLastArg(clang::driver::options::OPT_ffixed_form, 690 clang::driver::options::OPT_ffree_form)) { 691 opts.fortranForm = 692 arg->getOption().matches(clang::driver::options::OPT_ffixed_form) 693 ? FortranForm::FixedForm 694 : FortranForm::FreeForm; 695 } 696 697 // Set fixedFormColumns based on -ffixed-line-length=<value> 698 if (const auto *arg = 699 args.getLastArg(clang::driver::options::OPT_ffixed_line_length_EQ)) { 700 llvm::StringRef argValue = llvm::StringRef(arg->getValue()); 701 std::int64_t columns = -1; 702 if (argValue == "none") { 703 columns = 0; 704 } else if (argValue.getAsInteger(/*Radix=*/10, columns)) { 705 columns = -1; 706 } 707 if (columns < 0) { 708 diags.Report(clang::diag::err_drv_negative_columns) 709 << arg->getOption().getName() << arg->getValue(); 710 } else if (columns == 0) { 711 opts.fixedFormColumns = 1000000; 712 } else if (columns < 7) { 713 diags.Report(clang::diag::err_drv_small_columns) 714 << arg->getOption().getName() << arg->getValue() << "7"; 715 } else { 716 opts.fixedFormColumns = columns; 717 } 718 } 719 720 // Set conversion based on -fconvert=<value> 721 if (const auto *arg = 722 args.getLastArg(clang::driver::options::OPT_fconvert_EQ)) { 723 const char *argValue = arg->getValue(); 724 if (auto convert = parseConvertArg(argValue)) 725 opts.envDefaults.push_back({"FORT_CONVERT", *convert}); 726 else 727 diags.Report(clang::diag::err_drv_invalid_value) 728 << arg->getAsString(args) << argValue; 729 } 730 731 // -f{no-}implicit-none 732 opts.features.Enable( 733 Fortran::common::LanguageFeature::ImplicitNoneTypeAlways, 734 args.hasFlag(clang::driver::options::OPT_fimplicit_none, 735 clang::driver::options::OPT_fno_implicit_none, false)); 736 737 // -f{no-}backslash 738 opts.features.Enable(Fortran::common::LanguageFeature::BackslashEscapes, 739 args.hasFlag(clang::driver::options::OPT_fbackslash, 740 clang::driver::options::OPT_fno_backslash, 741 false)); 742 743 // -f{no-}logical-abbreviations 744 opts.features.Enable( 745 Fortran::common::LanguageFeature::LogicalAbbreviations, 746 args.hasFlag(clang::driver::options::OPT_flogical_abbreviations, 747 clang::driver::options::OPT_fno_logical_abbreviations, 748 false)); 749 750 // -f{no-}xor-operator 751 opts.features.Enable( 752 Fortran::common::LanguageFeature::XOROperator, 753 args.hasFlag(clang::driver::options::OPT_fxor_operator, 754 clang::driver::options::OPT_fno_xor_operator, false)); 755 756 // -fno-automatic 757 if (args.hasArg(clang::driver::options::OPT_fno_automatic)) { 758 opts.features.Enable(Fortran::common::LanguageFeature::DefaultSave); 759 } 760 761 if (args.hasArg( 762 clang::driver::options::OPT_falternative_parameter_statement)) { 763 opts.features.Enable(Fortran::common::LanguageFeature::OldStyleParameter); 764 } 765 if (const llvm::opt::Arg *arg = 766 args.getLastArg(clang::driver::options::OPT_finput_charset_EQ)) { 767 llvm::StringRef argValue = arg->getValue(); 768 if (argValue == "utf-8") { 769 opts.encoding = Fortran::parser::Encoding::UTF_8; 770 } else if (argValue == "latin-1") { 771 opts.encoding = Fortran::parser::Encoding::LATIN_1; 772 } else { 773 diags.Report(clang::diag::err_drv_invalid_value) 774 << arg->getAsString(args) << argValue; 775 } 776 } 777 778 setUpFrontendBasedOnAction(opts); 779 opts.dashX = dashX; 780 781 return diags.getNumErrors() == numErrorsBefore; 782 } 783 784 // Generate the path to look for intrinsic modules 785 static std::string getIntrinsicDir(const char *argv) { 786 // TODO: Find a system independent API 787 llvm::SmallString<128> driverPath; 788 driverPath.assign(llvm::sys::fs::getMainExecutable(argv, nullptr)); 789 llvm::sys::path::remove_filename(driverPath); 790 driverPath.append("/../include/flang/"); 791 return std::string(driverPath); 792 } 793 794 // Generate the path to look for OpenMP headers 795 static std::string getOpenMPHeadersDir(const char *argv) { 796 llvm::SmallString<128> includePath; 797 includePath.assign(llvm::sys::fs::getMainExecutable(argv, nullptr)); 798 llvm::sys::path::remove_filename(includePath); 799 includePath.append("/../include/flang/OpenMP/"); 800 return std::string(includePath); 801 } 802 803 /// Parses all preprocessor input arguments and populates the preprocessor 804 /// options accordingly. 805 /// 806 /// \param [in] opts The preprocessor options instance 807 /// \param [out] args The list of input arguments 808 static void parsePreprocessorArgs(Fortran::frontend::PreprocessorOptions &opts, 809 llvm::opt::ArgList &args) { 810 // Add macros from the command line. 811 for (const auto *currentArg : args.filtered(clang::driver::options::OPT_D, 812 clang::driver::options::OPT_U)) { 813 if (currentArg->getOption().matches(clang::driver::options::OPT_D)) { 814 opts.addMacroDef(currentArg->getValue()); 815 } else { 816 opts.addMacroUndef(currentArg->getValue()); 817 } 818 } 819 820 // Add the ordered list of -I's. 821 for (const auto *currentArg : args.filtered(clang::driver::options::OPT_I)) 822 opts.searchDirectoriesFromDashI.emplace_back(currentArg->getValue()); 823 824 // Prepend the ordered list of -intrinsic-modules-path 825 // to the default location to search. 826 for (const auto *currentArg : 827 args.filtered(clang::driver::options::OPT_fintrinsic_modules_path)) 828 opts.searchDirectoriesFromIntrModPath.emplace_back(currentArg->getValue()); 829 830 // -cpp/-nocpp 831 if (const auto *currentArg = args.getLastArg( 832 clang::driver::options::OPT_cpp, clang::driver::options::OPT_nocpp)) 833 opts.macrosFlag = 834 (currentArg->getOption().matches(clang::driver::options::OPT_cpp)) 835 ? PPMacrosFlag::Include 836 : PPMacrosFlag::Exclude; 837 838 opts.noReformat = args.hasArg(clang::driver::options::OPT_fno_reformat); 839 opts.preprocessIncludeLines = 840 args.hasArg(clang::driver::options::OPT_fpreprocess_include_lines); 841 opts.noLineDirectives = args.hasArg(clang::driver::options::OPT_P); 842 opts.showMacros = args.hasArg(clang::driver::options::OPT_dM); 843 } 844 845 /// Parses all semantic related arguments and populates the variables 846 /// options accordingly. Returns false if new errors are generated. 847 static bool parseSemaArgs(CompilerInvocation &res, llvm::opt::ArgList &args, 848 clang::DiagnosticsEngine &diags) { 849 unsigned numErrorsBefore = diags.getNumErrors(); 850 851 // -J/module-dir option 852 std::vector<std::string> moduleDirList = 853 args.getAllArgValues(clang::driver::options::OPT_module_dir); 854 // User can only specify one -J/-module-dir directory, but may repeat 855 // -J/-module-dir as long as the directory is the same each time. 856 // https://gcc.gnu.org/onlinedocs/gfortran/Directory-Options.html 857 std::sort(moduleDirList.begin(), moduleDirList.end()); 858 moduleDirList.erase(std::unique(moduleDirList.begin(), moduleDirList.end()), 859 moduleDirList.end()); 860 if (moduleDirList.size() > 1) { 861 const unsigned diagID = 862 diags.getCustomDiagID(clang::DiagnosticsEngine::Error, 863 "Only one '-module-dir/-J' directory allowed. " 864 "'-module-dir/-J' may be given multiple times " 865 "but the directory must be the same each time."); 866 diags.Report(diagID); 867 } 868 if (moduleDirList.size() == 1) 869 res.setModuleDir(moduleDirList[0]); 870 871 // -fdebug-module-writer option 872 if (args.hasArg(clang::driver::options::OPT_fdebug_module_writer)) { 873 res.setDebugModuleDir(true); 874 } 875 876 // -fhermetic-module-files option 877 if (args.hasArg(clang::driver::options::OPT_fhermetic_module_files)) { 878 res.setHermeticModuleFileOutput(true); 879 } 880 881 // -module-suffix 882 if (const auto *moduleSuffix = 883 args.getLastArg(clang::driver::options::OPT_module_suffix)) { 884 res.setModuleFileSuffix(moduleSuffix->getValue()); 885 } 886 887 // -f{no-}analyzed-objects-for-unparse 888 res.setUseAnalyzedObjectsForUnparse(args.hasFlag( 889 clang::driver::options::OPT_fanalyzed_objects_for_unparse, 890 clang::driver::options::OPT_fno_analyzed_objects_for_unparse, true)); 891 892 return diags.getNumErrors() == numErrorsBefore; 893 } 894 895 /// Parses all diagnostics related arguments and populates the variables 896 /// options accordingly. Returns false if new errors are generated. 897 static bool parseDiagArgs(CompilerInvocation &res, llvm::opt::ArgList &args, 898 clang::DiagnosticsEngine &diags) { 899 unsigned numErrorsBefore = diags.getNumErrors(); 900 901 // -Werror option 902 // TODO: Currently throws a Diagnostic for anything other than -W<error>, 903 // this has to change when other -W<opt>'s are supported. 904 if (args.hasArg(clang::driver::options::OPT_W_Joined)) { 905 const auto &wArgs = 906 args.getAllArgValues(clang::driver::options::OPT_W_Joined); 907 for (const auto &wArg : wArgs) { 908 if (wArg == "error") { 909 res.setWarnAsErr(true); 910 } else { 911 const unsigned diagID = 912 diags.getCustomDiagID(clang::DiagnosticsEngine::Error, 913 "Only `-Werror` is supported currently."); 914 diags.Report(diagID); 915 } 916 } 917 } 918 919 // Default to off for `flang -fc1`. 920 res.getFrontendOpts().showColors = 921 parseShowColorsArgs(args, /*defaultDiagColor=*/false); 922 923 // Honor color diagnostics. 924 res.getDiagnosticOpts().ShowColors = res.getFrontendOpts().showColors; 925 926 return diags.getNumErrors() == numErrorsBefore; 927 } 928 929 /// Parses all Dialect related arguments and populates the variables 930 /// options accordingly. Returns false if new errors are generated. 931 static bool parseDialectArgs(CompilerInvocation &res, llvm::opt::ArgList &args, 932 clang::DiagnosticsEngine &diags) { 933 unsigned numErrorsBefore = diags.getNumErrors(); 934 935 // -fdefault* family 936 if (args.hasArg(clang::driver::options::OPT_fdefault_real_8)) { 937 res.getDefaultKinds().set_defaultRealKind(8); 938 res.getDefaultKinds().set_doublePrecisionKind(16); 939 } 940 if (args.hasArg(clang::driver::options::OPT_fdefault_integer_8)) { 941 res.getDefaultKinds().set_defaultIntegerKind(8); 942 res.getDefaultKinds().set_subscriptIntegerKind(8); 943 res.getDefaultKinds().set_sizeIntegerKind(8); 944 res.getDefaultKinds().set_defaultLogicalKind(8); 945 } 946 if (args.hasArg(clang::driver::options::OPT_fdefault_double_8)) { 947 if (!args.hasArg(clang::driver::options::OPT_fdefault_real_8)) { 948 // -fdefault-double-8 has to be used with -fdefault-real-8 949 // to be compatible with gfortran 950 const unsigned diagID = diags.getCustomDiagID( 951 clang::DiagnosticsEngine::Error, 952 "Use of `-fdefault-double-8` requires `-fdefault-real-8`"); 953 diags.Report(diagID); 954 } 955 // https://gcc.gnu.org/onlinedocs/gfortran/Fortran-Dialect-Options.html 956 res.getDefaultKinds().set_doublePrecisionKind(8); 957 } 958 if (args.hasArg(clang::driver::options::OPT_flarge_sizes)) 959 res.getDefaultKinds().set_sizeIntegerKind(8); 960 961 // -x cuda 962 auto language = args.getLastArgValue(clang::driver::options::OPT_x); 963 if (language == "cuda") { 964 res.getFrontendOpts().features.Enable( 965 Fortran::common::LanguageFeature::CUDA); 966 } 967 968 // -fopenacc 969 if (args.hasArg(clang::driver::options::OPT_fopenacc)) { 970 res.getFrontendOpts().features.Enable( 971 Fortran::common::LanguageFeature::OpenACC); 972 } 973 974 // -pedantic 975 if (args.hasArg(clang::driver::options::OPT_pedantic)) { 976 res.setEnableConformanceChecks(); 977 res.setEnableUsageChecks(); 978 } 979 980 // -w 981 if (args.hasArg(clang::driver::options::OPT_w)) 982 res.setDisableWarnings(); 983 984 // -std=f2018 985 // TODO: Set proper options when more fortran standards 986 // are supported. 987 if (args.hasArg(clang::driver::options::OPT_std_EQ)) { 988 auto standard = args.getLastArgValue(clang::driver::options::OPT_std_EQ); 989 // We only allow f2018 as the given standard 990 if (standard == "f2018") { 991 res.setEnableConformanceChecks(); 992 } else { 993 const unsigned diagID = 994 diags.getCustomDiagID(clang::DiagnosticsEngine::Error, 995 "Only -std=f2018 is allowed currently."); 996 diags.Report(diagID); 997 } 998 } 999 return diags.getNumErrors() == numErrorsBefore; 1000 } 1001 1002 /// Parses all OpenMP related arguments if the -fopenmp option is present, 1003 /// populating the \c res object accordingly. Returns false if new errors are 1004 /// generated. 1005 static bool parseOpenMPArgs(CompilerInvocation &res, llvm::opt::ArgList &args, 1006 clang::DiagnosticsEngine &diags) { 1007 llvm::opt::Arg *arg = args.getLastArg(clang::driver::options::OPT_fopenmp, 1008 clang::driver::options::OPT_fno_openmp); 1009 if (!arg || arg->getOption().matches(clang::driver::options::OPT_fno_openmp)) 1010 return true; 1011 1012 unsigned numErrorsBefore = diags.getNumErrors(); 1013 llvm::Triple t(res.getTargetOpts().triple); 1014 1015 // By default OpenMP is set to 1.1 version 1016 res.getLangOpts().OpenMPVersion = 11; 1017 res.getFrontendOpts().features.Enable( 1018 Fortran::common::LanguageFeature::OpenMP); 1019 if (int Version = getLastArgIntValue( 1020 args, clang::driver::options::OPT_fopenmp_version_EQ, 1021 res.getLangOpts().OpenMPVersion, diags)) { 1022 res.getLangOpts().OpenMPVersion = Version; 1023 } 1024 if (args.hasArg(clang::driver::options::OPT_fopenmp_force_usm)) { 1025 res.getLangOpts().OpenMPForceUSM = 1; 1026 } 1027 if (args.hasArg(clang::driver::options::OPT_fopenmp_is_target_device)) { 1028 res.getLangOpts().OpenMPIsTargetDevice = 1; 1029 1030 // Get OpenMP host file path if any and report if a non existent file is 1031 // found 1032 if (auto *arg = args.getLastArg( 1033 clang::driver::options::OPT_fopenmp_host_ir_file_path)) { 1034 res.getLangOpts().OMPHostIRFile = arg->getValue(); 1035 if (!llvm::sys::fs::exists(res.getLangOpts().OMPHostIRFile)) 1036 diags.Report(clang::diag::err_drv_omp_host_ir_file_not_found) 1037 << res.getLangOpts().OMPHostIRFile; 1038 } 1039 1040 if (args.hasFlag( 1041 clang::driver::options::OPT_fopenmp_assume_teams_oversubscription, 1042 clang::driver::options:: 1043 OPT_fno_openmp_assume_teams_oversubscription, 1044 /*Default=*/false)) 1045 res.getLangOpts().OpenMPTeamSubscription = true; 1046 1047 if (args.hasArg(clang::driver::options::OPT_fopenmp_assume_no_thread_state)) 1048 res.getLangOpts().OpenMPNoThreadState = 1; 1049 1050 if (args.hasArg( 1051 clang::driver::options::OPT_fopenmp_assume_no_nested_parallelism)) 1052 res.getLangOpts().OpenMPNoNestedParallelism = 1; 1053 1054 if (args.hasFlag( 1055 clang::driver::options::OPT_fopenmp_assume_threads_oversubscription, 1056 clang::driver::options:: 1057 OPT_fno_openmp_assume_threads_oversubscription, 1058 /*Default=*/false)) 1059 res.getLangOpts().OpenMPThreadSubscription = true; 1060 1061 if ((args.hasArg(clang::driver::options::OPT_fopenmp_target_debug) || 1062 args.hasArg(clang::driver::options::OPT_fopenmp_target_debug_EQ))) { 1063 res.getLangOpts().OpenMPTargetDebug = getLastArgIntValue( 1064 args, clang::driver::options::OPT_fopenmp_target_debug_EQ, 1065 res.getLangOpts().OpenMPTargetDebug, diags); 1066 1067 if (!res.getLangOpts().OpenMPTargetDebug && 1068 args.hasArg(clang::driver::options::OPT_fopenmp_target_debug)) 1069 res.getLangOpts().OpenMPTargetDebug = 1; 1070 } 1071 if (args.hasArg(clang::driver::options::OPT_nogpulib)) 1072 res.getLangOpts().NoGPULib = 1; 1073 } 1074 1075 switch (llvm::Triple(res.getTargetOpts().triple).getArch()) { 1076 case llvm::Triple::nvptx: 1077 case llvm::Triple::nvptx64: 1078 case llvm::Triple::amdgcn: 1079 if (!res.getLangOpts().OpenMPIsTargetDevice) { 1080 const unsigned diagID = diags.getCustomDiagID( 1081 clang::DiagnosticsEngine::Error, 1082 "OpenMP AMDGPU/NVPTX is only prepared to deal with device code."); 1083 diags.Report(diagID); 1084 } 1085 res.getLangOpts().OpenMPIsGPU = 1; 1086 break; 1087 default: 1088 res.getLangOpts().OpenMPIsGPU = 0; 1089 break; 1090 } 1091 1092 // Get the OpenMP target triples if any. 1093 if (auto *arg = 1094 args.getLastArg(clang::driver::options::OPT_fopenmp_targets_EQ)) { 1095 enum ArchPtrSize { Arch16Bit, Arch32Bit, Arch64Bit }; 1096 auto getArchPtrSize = [](const llvm::Triple &triple) { 1097 if (triple.isArch16Bit()) 1098 return Arch16Bit; 1099 if (triple.isArch32Bit()) 1100 return Arch32Bit; 1101 assert(triple.isArch64Bit() && "Expected 64-bit architecture"); 1102 return Arch64Bit; 1103 }; 1104 1105 for (unsigned i = 0; i < arg->getNumValues(); ++i) { 1106 llvm::Triple tt(arg->getValue(i)); 1107 1108 if (tt.getArch() == llvm::Triple::UnknownArch || 1109 !(tt.getArch() == llvm::Triple::aarch64 || tt.isPPC() || 1110 tt.getArch() == llvm::Triple::systemz || 1111 tt.getArch() == llvm::Triple::nvptx || 1112 tt.getArch() == llvm::Triple::nvptx64 || 1113 tt.getArch() == llvm::Triple::amdgcn || 1114 tt.getArch() == llvm::Triple::x86 || 1115 tt.getArch() == llvm::Triple::x86_64)) 1116 diags.Report(clang::diag::err_drv_invalid_omp_target) 1117 << arg->getValue(i); 1118 else if (getArchPtrSize(t) != getArchPtrSize(tt)) 1119 diags.Report(clang::diag::err_drv_incompatible_omp_arch) 1120 << arg->getValue(i) << t.str(); 1121 else 1122 res.getLangOpts().OMPTargetTriples.push_back(tt); 1123 } 1124 } 1125 return diags.getNumErrors() == numErrorsBefore; 1126 } 1127 1128 /// Parses signed integer overflow options and populates the 1129 /// CompilerInvocation accordingly. 1130 /// Returns false if new errors are generated. 1131 /// 1132 /// \param [out] invoc Stores the processed arguments 1133 /// \param [in] args The compiler invocation arguments to parse 1134 /// \param [out] diags DiagnosticsEngine to report erros with 1135 static bool parseIntegerOverflowArgs(CompilerInvocation &invoc, 1136 llvm::opt::ArgList &args, 1137 clang::DiagnosticsEngine &diags) { 1138 Fortran::common::LangOptions &opts = invoc.getLangOpts(); 1139 1140 if (args.getLastArg(clang::driver::options::OPT_fwrapv)) 1141 opts.setSignedOverflowBehavior(Fortran::common::LangOptions::SOB_Defined); 1142 1143 return true; 1144 } 1145 1146 /// Parses all floating point related arguments and populates the 1147 /// CompilerInvocation accordingly. 1148 /// Returns false if new errors are generated. 1149 /// 1150 /// \param [out] invoc Stores the processed arguments 1151 /// \param [in] args The compiler invocation arguments to parse 1152 /// \param [out] diags DiagnosticsEngine to report erros with 1153 static bool parseFloatingPointArgs(CompilerInvocation &invoc, 1154 llvm::opt::ArgList &args, 1155 clang::DiagnosticsEngine &diags) { 1156 Fortran::common::LangOptions &opts = invoc.getLangOpts(); 1157 1158 if (const llvm::opt::Arg *a = 1159 args.getLastArg(clang::driver::options::OPT_ffp_contract)) { 1160 const llvm::StringRef val = a->getValue(); 1161 enum Fortran::common::LangOptions::FPModeKind fpContractMode; 1162 1163 if (val == "off") 1164 fpContractMode = Fortran::common::LangOptions::FPM_Off; 1165 else if (val == "fast") 1166 fpContractMode = Fortran::common::LangOptions::FPM_Fast; 1167 else { 1168 diags.Report(clang::diag::err_drv_unsupported_option_argument) 1169 << a->getSpelling() << val; 1170 return false; 1171 } 1172 1173 opts.setFPContractMode(fpContractMode); 1174 } 1175 1176 if (args.getLastArg(clang::driver::options::OPT_menable_no_infs)) { 1177 opts.NoHonorInfs = true; 1178 } 1179 1180 if (args.getLastArg(clang::driver::options::OPT_menable_no_nans)) { 1181 opts.NoHonorNaNs = true; 1182 } 1183 1184 if (args.getLastArg(clang::driver::options::OPT_fapprox_func)) { 1185 opts.ApproxFunc = true; 1186 } 1187 1188 if (args.getLastArg(clang::driver::options::OPT_fno_signed_zeros)) { 1189 opts.NoSignedZeros = true; 1190 } 1191 1192 if (args.getLastArg(clang::driver::options::OPT_mreassociate)) { 1193 opts.AssociativeMath = true; 1194 } 1195 1196 if (args.getLastArg(clang::driver::options::OPT_freciprocal_math)) { 1197 opts.ReciprocalMath = true; 1198 } 1199 1200 if (args.getLastArg(clang::driver::options::OPT_ffast_math)) { 1201 opts.NoHonorInfs = true; 1202 opts.NoHonorNaNs = true; 1203 opts.AssociativeMath = true; 1204 opts.ReciprocalMath = true; 1205 opts.ApproxFunc = true; 1206 opts.NoSignedZeros = true; 1207 opts.setFPContractMode(Fortran::common::LangOptions::FPM_Fast); 1208 } 1209 1210 return true; 1211 } 1212 1213 /// Parses vscale range options and populates the CompilerInvocation 1214 /// accordingly. 1215 /// Returns false if new errors are generated. 1216 /// 1217 /// \param [out] invoc Stores the processed arguments 1218 /// \param [in] args The compiler invocation arguments to parse 1219 /// \param [out] diags DiagnosticsEngine to report erros with 1220 static bool parseVScaleArgs(CompilerInvocation &invoc, llvm::opt::ArgList &args, 1221 clang::DiagnosticsEngine &diags) { 1222 const auto *vscaleMin = 1223 args.getLastArg(clang::driver::options::OPT_mvscale_min_EQ); 1224 const auto *vscaleMax = 1225 args.getLastArg(clang::driver::options::OPT_mvscale_max_EQ); 1226 1227 if (!vscaleMin && !vscaleMax) 1228 return true; 1229 1230 llvm::Triple triple = llvm::Triple(invoc.getTargetOpts().triple); 1231 if (!triple.isAArch64() && !triple.isRISCV()) { 1232 const unsigned diagID = 1233 diags.getCustomDiagID(clang::DiagnosticsEngine::Error, 1234 "`-mvscale-max` and `-mvscale-min` are not " 1235 "supported for this architecture: %0"); 1236 diags.Report(diagID) << triple.getArchName(); 1237 return false; 1238 } 1239 1240 Fortran::common::LangOptions &opts = invoc.getLangOpts(); 1241 if (vscaleMin) { 1242 llvm::StringRef argValue = llvm::StringRef(vscaleMin->getValue()); 1243 unsigned vscaleMinVal; 1244 if (argValue.getAsInteger(/*Radix=*/10, vscaleMinVal)) { 1245 diags.Report(clang::diag::err_drv_unsupported_option_argument) 1246 << vscaleMax->getSpelling() << argValue; 1247 return false; 1248 } 1249 opts.VScaleMin = vscaleMinVal; 1250 } 1251 1252 if (vscaleMax) { 1253 llvm::StringRef argValue = llvm::StringRef(vscaleMax->getValue()); 1254 unsigned vscaleMaxVal; 1255 if (argValue.getAsInteger(/*Radix=w*/ 10, vscaleMaxVal)) { 1256 diags.Report(clang::diag::err_drv_unsupported_option_argument) 1257 << vscaleMax->getSpelling() << argValue; 1258 return false; 1259 } 1260 opts.VScaleMax = vscaleMaxVal; 1261 } 1262 return true; 1263 } 1264 1265 static bool parseLinkerOptionsArgs(CompilerInvocation &invoc, 1266 llvm::opt::ArgList &args, 1267 clang::DiagnosticsEngine &diags) { 1268 llvm::Triple triple = llvm::Triple(invoc.getTargetOpts().triple); 1269 1270 // TODO: support --dependent-lib on other platforms when MLIR supports 1271 // !llvm.dependent.lib 1272 if (args.hasArg(clang::driver::options::OPT_dependent_lib) && 1273 !triple.isOSWindows()) { 1274 const unsigned diagID = 1275 diags.getCustomDiagID(clang::DiagnosticsEngine::Error, 1276 "--dependent-lib is only supported on Windows"); 1277 diags.Report(diagID); 1278 return false; 1279 } 1280 1281 invoc.getCodeGenOpts().DependentLibs = 1282 args.getAllArgValues(clang::driver::options::OPT_dependent_lib); 1283 return true; 1284 } 1285 1286 static bool parseLangOptionsArgs(CompilerInvocation &invoc, 1287 llvm::opt::ArgList &args, 1288 clang::DiagnosticsEngine &diags) { 1289 bool success = true; 1290 1291 success &= parseIntegerOverflowArgs(invoc, args, diags); 1292 success &= parseFloatingPointArgs(invoc, args, diags); 1293 success &= parseVScaleArgs(invoc, args, diags); 1294 1295 return success; 1296 } 1297 1298 bool CompilerInvocation::createFromArgs( 1299 CompilerInvocation &invoc, llvm::ArrayRef<const char *> commandLineArgs, 1300 clang::DiagnosticsEngine &diags, const char *argv0) { 1301 1302 bool success = true; 1303 1304 // Set the default triple for this CompilerInvocation. This might be 1305 // overridden by users with `-triple` (see the call to `ParseTargetArgs` 1306 // below). 1307 // NOTE: Like in Clang, it would be nice to use option marshalling 1308 // for this so that the entire logic for setting-up the triple is in one 1309 // place. 1310 invoc.getTargetOpts().triple = 1311 llvm::Triple::normalize(llvm::sys::getDefaultTargetTriple()); 1312 1313 // Parse the arguments 1314 const llvm::opt::OptTable &opts = clang::driver::getDriverOptTable(); 1315 llvm::opt::Visibility visibilityMask(clang::driver::options::FC1Option); 1316 unsigned missingArgIndex, missingArgCount; 1317 llvm::opt::InputArgList args = opts.ParseArgs( 1318 commandLineArgs, missingArgIndex, missingArgCount, visibilityMask); 1319 1320 // Check for missing argument error. 1321 if (missingArgCount) { 1322 diags.Report(clang::diag::err_drv_missing_argument) 1323 << args.getArgString(missingArgIndex) << missingArgCount; 1324 success = false; 1325 } 1326 1327 // Issue errors on unknown arguments 1328 for (const auto *a : args.filtered(clang::driver::options::OPT_UNKNOWN)) { 1329 auto argString = a->getAsString(args); 1330 std::string nearest; 1331 if (opts.findNearest(argString, nearest, visibilityMask) > 1) 1332 diags.Report(clang::diag::err_drv_unknown_argument) << argString; 1333 else 1334 diags.Report(clang::diag::err_drv_unknown_argument_with_suggestion) 1335 << argString << nearest; 1336 success = false; 1337 } 1338 1339 // -flang-experimental-hlfir 1340 if (args.hasArg(clang::driver::options::OPT_flang_experimental_hlfir) || 1341 args.hasArg(clang::driver::options::OPT_emit_hlfir)) { 1342 invoc.loweringOpts.setLowerToHighLevelFIR(true); 1343 } 1344 1345 // -flang-deprecated-no-hlfir 1346 if (args.hasArg(clang::driver::options::OPT_flang_deprecated_no_hlfir) && 1347 !args.hasArg(clang::driver::options::OPT_emit_hlfir)) { 1348 if (args.hasArg(clang::driver::options::OPT_flang_experimental_hlfir)) { 1349 const unsigned diagID = diags.getCustomDiagID( 1350 clang::DiagnosticsEngine::Error, 1351 "Options '-flang-experimental-hlfir' and " 1352 "'-flang-deprecated-no-hlfir' cannot be both specified"); 1353 diags.Report(diagID); 1354 } 1355 invoc.loweringOpts.setLowerToHighLevelFIR(false); 1356 } 1357 1358 // -fno-ppc-native-vector-element-order 1359 if (args.hasArg(clang::driver::options::OPT_fno_ppc_native_vec_elem_order)) { 1360 invoc.loweringOpts.setNoPPCNativeVecElemOrder(true); 1361 } 1362 1363 // -flang-experimental-integer-overflow 1364 if (args.hasArg( 1365 clang::driver::options::OPT_flang_experimental_integer_overflow)) { 1366 invoc.loweringOpts.setNSWOnLoopVarInc(true); 1367 } 1368 1369 // Preserve all the remark options requested, i.e. -Rpass, -Rpass-missed or 1370 // -Rpass-analysis. This will be used later when processing and outputting the 1371 // remarks generated by LLVM in ExecuteCompilerInvocation.cpp. 1372 for (auto *a : args.filtered(clang::driver::options::OPT_R_Group)) { 1373 if (a->getOption().matches(clang::driver::options::OPT_R_value_Group)) 1374 // This is -Rfoo=, where foo is the name of the diagnostic 1375 // group. Add only the remark option name to the diagnostics. e.g. for 1376 // -Rpass= we will add the string "pass". 1377 invoc.getDiagnosticOpts().Remarks.push_back( 1378 std::string(a->getOption().getName().drop_front(1).rtrim("=-"))); 1379 else 1380 // If no regex was provided, add the provided value, e.g. for -Rpass add 1381 // the string "pass". 1382 invoc.getDiagnosticOpts().Remarks.push_back(a->getValue()); 1383 } 1384 1385 success &= parseFrontendArgs(invoc.getFrontendOpts(), args, diags); 1386 parseTargetArgs(invoc.getTargetOpts(), args); 1387 parsePreprocessorArgs(invoc.getPreprocessorOpts(), args); 1388 parseCodeGenArgs(invoc.getCodeGenOpts(), args, diags); 1389 success &= parseDebugArgs(invoc.getCodeGenOpts(), args, diags); 1390 success &= parseVectorLibArg(invoc.getCodeGenOpts(), args, diags); 1391 success &= parseSemaArgs(invoc, args, diags); 1392 success &= parseDialectArgs(invoc, args, diags); 1393 success &= parseOpenMPArgs(invoc, args, diags); 1394 success &= parseDiagArgs(invoc, args, diags); 1395 1396 // Collect LLVM (-mllvm) and MLIR (-mmlir) options. 1397 // NOTE: Try to avoid adding any options directly to `llvmArgs` or 1398 // `mlirArgs`. Instead, you can use 1399 // * `-mllvm <your-llvm-option>`, or 1400 // * `-mmlir <your-mlir-option>`. 1401 invoc.frontendOpts.llvmArgs = 1402 args.getAllArgValues(clang::driver::options::OPT_mllvm); 1403 invoc.frontendOpts.mlirArgs = 1404 args.getAllArgValues(clang::driver::options::OPT_mmlir); 1405 1406 success &= parseLangOptionsArgs(invoc, args, diags); 1407 1408 success &= parseLinkerOptionsArgs(invoc, args, diags); 1409 1410 // Set the string to be used as the return value of the COMPILER_OPTIONS 1411 // intrinsic of iso_fortran_env. This is either passed in from the parent 1412 // compiler driver invocation with an environment variable, or failing that 1413 // set to the command line arguments of the frontend driver invocation. 1414 invoc.allCompilerInvocOpts = std::string(); 1415 llvm::raw_string_ostream os(invoc.allCompilerInvocOpts); 1416 char *compilerOptsEnv = std::getenv("FLANG_COMPILER_OPTIONS_STRING"); 1417 if (compilerOptsEnv != nullptr) { 1418 os << compilerOptsEnv; 1419 } else { 1420 os << argv0 << ' '; 1421 for (auto it = commandLineArgs.begin(), e = commandLineArgs.end(); it != e; 1422 ++it) { 1423 os << ' ' << *it; 1424 } 1425 } 1426 1427 invoc.setArgv0(argv0); 1428 1429 return success; 1430 } 1431 1432 void CompilerInvocation::collectMacroDefinitions() { 1433 auto &ppOpts = this->getPreprocessorOpts(); 1434 1435 for (unsigned i = 0, n = ppOpts.macros.size(); i != n; ++i) { 1436 llvm::StringRef macro = ppOpts.macros[i].first; 1437 bool isUndef = ppOpts.macros[i].second; 1438 1439 std::pair<llvm::StringRef, llvm::StringRef> macroPair = macro.split('='); 1440 llvm::StringRef macroName = macroPair.first; 1441 llvm::StringRef macroBody = macroPair.second; 1442 1443 // For an #undef'd macro, we only care about the name. 1444 if (isUndef) { 1445 parserOpts.predefinitions.emplace_back(macroName.str(), 1446 std::optional<std::string>{}); 1447 continue; 1448 } 1449 1450 // For a #define'd macro, figure out the actual definition. 1451 if (macroName.size() == macro.size()) 1452 macroBody = "1"; 1453 else { 1454 // Note: GCC drops anything following an end-of-line character. 1455 llvm::StringRef::size_type end = macroBody.find_first_of("\n\r"); 1456 macroBody = macroBody.substr(0, end); 1457 } 1458 parserOpts.predefinitions.emplace_back( 1459 macroName, std::optional<std::string>(macroBody.str())); 1460 } 1461 } 1462 1463 void CompilerInvocation::setDefaultFortranOpts() { 1464 auto &fortranOptions = getFortranOpts(); 1465 1466 std::vector<std::string> searchDirectories{"."s}; 1467 fortranOptions.searchDirectories = searchDirectories; 1468 1469 // Add the location of omp_lib.h to the search directories. Currently this is 1470 // identical to the modules' directory. 1471 fortranOptions.searchDirectories.emplace_back( 1472 getOpenMPHeadersDir(getArgv0())); 1473 1474 fortranOptions.isFixedForm = false; 1475 } 1476 1477 // TODO: When expanding this method, consider creating a dedicated API for 1478 // this. Also at some point we will need to differentiate between different 1479 // targets and add dedicated predefines for each. 1480 void CompilerInvocation::setDefaultPredefinitions() { 1481 auto &fortranOptions = getFortranOpts(); 1482 const auto &frontendOptions = getFrontendOpts(); 1483 // Populate the macro list with version numbers and other predefinitions. 1484 fortranOptions.predefinitions.emplace_back("__flang__", "1"); 1485 fortranOptions.predefinitions.emplace_back("__flang_major__", 1486 FLANG_VERSION_MAJOR_STRING); 1487 fortranOptions.predefinitions.emplace_back("__flang_minor__", 1488 FLANG_VERSION_MINOR_STRING); 1489 fortranOptions.predefinitions.emplace_back("__flang_patchlevel__", 1490 FLANG_VERSION_PATCHLEVEL_STRING); 1491 1492 // Add predefinitions based on extensions enabled 1493 if (frontendOptions.features.IsEnabled( 1494 Fortran::common::LanguageFeature::OpenACC)) { 1495 fortranOptions.predefinitions.emplace_back("_OPENACC", "202211"); 1496 } 1497 if (frontendOptions.features.IsEnabled( 1498 Fortran::common::LanguageFeature::OpenMP)) { 1499 Fortran::common::setOpenMPMacro(getLangOpts().OpenMPVersion, 1500 fortranOptions.predefinitions); 1501 } 1502 1503 llvm::Triple targetTriple{llvm::Triple(this->targetOpts.triple)}; 1504 if (targetTriple.isPPC()) { 1505 // '__powerpc__' is a generic macro for any PowerPC cases. e.g. Max integer 1506 // size. 1507 fortranOptions.predefinitions.emplace_back("__powerpc__", "1"); 1508 } 1509 if (targetTriple.isOSLinux()) { 1510 fortranOptions.predefinitions.emplace_back("__linux__", "1"); 1511 } 1512 1513 switch (targetTriple.getArch()) { 1514 default: 1515 break; 1516 case llvm::Triple::ArchType::x86_64: 1517 fortranOptions.predefinitions.emplace_back("__x86_64__", "1"); 1518 fortranOptions.predefinitions.emplace_back("__x86_64", "1"); 1519 break; 1520 } 1521 } 1522 1523 void CompilerInvocation::setFortranOpts() { 1524 auto &fortranOptions = getFortranOpts(); 1525 const auto &frontendOptions = getFrontendOpts(); 1526 const auto &preprocessorOptions = getPreprocessorOpts(); 1527 auto &moduleDirJ = getModuleDir(); 1528 1529 if (frontendOptions.fortranForm != FortranForm::Unknown) { 1530 fortranOptions.isFixedForm = 1531 frontendOptions.fortranForm == FortranForm::FixedForm; 1532 } 1533 fortranOptions.fixedFormColumns = frontendOptions.fixedFormColumns; 1534 1535 // -E 1536 fortranOptions.prescanAndReformat = 1537 frontendOptions.programAction == PrintPreprocessedInput; 1538 1539 fortranOptions.features = frontendOptions.features; 1540 fortranOptions.encoding = frontendOptions.encoding; 1541 1542 // Adding search directories specified by -I 1543 fortranOptions.searchDirectories.insert( 1544 fortranOptions.searchDirectories.end(), 1545 preprocessorOptions.searchDirectoriesFromDashI.begin(), 1546 preprocessorOptions.searchDirectoriesFromDashI.end()); 1547 1548 // Add the ordered list of -intrinsic-modules-path 1549 fortranOptions.searchDirectories.insert( 1550 fortranOptions.searchDirectories.end(), 1551 preprocessorOptions.searchDirectoriesFromIntrModPath.begin(), 1552 preprocessorOptions.searchDirectoriesFromIntrModPath.end()); 1553 1554 // Add the default intrinsic module directory 1555 fortranOptions.intrinsicModuleDirectories.emplace_back( 1556 getIntrinsicDir(getArgv0())); 1557 1558 // Add the directory supplied through -J/-module-dir to the list of search 1559 // directories 1560 if (moduleDirJ != ".") 1561 fortranOptions.searchDirectories.emplace_back(moduleDirJ); 1562 1563 if (frontendOptions.instrumentedParse) 1564 fortranOptions.instrumentedParse = true; 1565 1566 if (frontendOptions.showColors) 1567 fortranOptions.showColors = true; 1568 1569 if (frontendOptions.needProvenanceRangeToCharBlockMappings) 1570 fortranOptions.needProvenanceRangeToCharBlockMappings = true; 1571 1572 if (getEnableConformanceChecks()) 1573 fortranOptions.features.WarnOnAllNonstandard(); 1574 1575 if (getEnableUsageChecks()) 1576 fortranOptions.features.WarnOnAllUsage(); 1577 1578 if (getDisableWarnings()) { 1579 fortranOptions.features.DisableAllNonstandardWarnings(); 1580 fortranOptions.features.DisableAllUsageWarnings(); 1581 } 1582 } 1583 1584 std::unique_ptr<Fortran::semantics::SemanticsContext> 1585 CompilerInvocation::getSemanticsCtx( 1586 Fortran::parser::AllCookedSources &allCookedSources, 1587 const llvm::TargetMachine &targetMachine) { 1588 auto &fortranOptions = getFortranOpts(); 1589 1590 auto semanticsContext = std::make_unique<semantics::SemanticsContext>( 1591 getDefaultKinds(), fortranOptions.features, getLangOpts(), 1592 allCookedSources); 1593 1594 semanticsContext->set_moduleDirectory(getModuleDir()) 1595 .set_searchDirectories(fortranOptions.searchDirectories) 1596 .set_intrinsicModuleDirectories(fortranOptions.intrinsicModuleDirectories) 1597 .set_warningsAreErrors(getWarnAsErr()) 1598 .set_moduleFileSuffix(getModuleFileSuffix()) 1599 .set_underscoring(getCodeGenOpts().Underscoring); 1600 1601 std::string compilerVersion = Fortran::common::getFlangFullVersion(); 1602 Fortran::tools::setUpTargetCharacteristics( 1603 semanticsContext->targetCharacteristics(), targetMachine, getTargetOpts(), 1604 compilerVersion, allCompilerInvocOpts); 1605 return semanticsContext; 1606 } 1607 1608 /// Set \p loweringOptions controlling lowering behavior based 1609 /// on the \p optimizationLevel. 1610 void CompilerInvocation::setLoweringOptions() { 1611 const CodeGenOptions &codegenOpts = getCodeGenOpts(); 1612 1613 // Lower TRANSPOSE as a runtime call under -O0. 1614 loweringOpts.setOptimizeTranspose(codegenOpts.OptimizationLevel > 0); 1615 loweringOpts.setUnderscoring(codegenOpts.Underscoring); 1616 1617 const Fortran::common::LangOptions &langOptions = getLangOpts(); 1618 loweringOpts.setIntegerWrapAround(langOptions.getSignedOverflowBehavior() == 1619 Fortran::common::LangOptions::SOB_Defined); 1620 Fortran::common::MathOptionsBase &mathOpts = loweringOpts.getMathOptions(); 1621 // TODO: when LangOptions are finalized, we can represent 1622 // the math related options using Fortran::commmon::MathOptionsBase, 1623 // so that we can just copy it into LoweringOptions. 1624 mathOpts 1625 .setFPContractEnabled(langOptions.getFPContractMode() == 1626 Fortran::common::LangOptions::FPM_Fast) 1627 .setNoHonorInfs(langOptions.NoHonorInfs) 1628 .setNoHonorNaNs(langOptions.NoHonorNaNs) 1629 .setApproxFunc(langOptions.ApproxFunc) 1630 .setNoSignedZeros(langOptions.NoSignedZeros) 1631 .setAssociativeMath(langOptions.AssociativeMath) 1632 .setReciprocalMath(langOptions.ReciprocalMath); 1633 } 1634