| 1 | //===--- CommonArgs.cpp - Args handling for multiple toolchains -*- C++ -*-===// |
| 2 | // |
| 3 | // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. |
| 4 | // See https://llvm.org/LICENSE.txt for license information. |
| 5 | // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception |
| 6 | // |
| 7 | //===----------------------------------------------------------------------===// |
| 8 | |
| 9 | #include "clang/Driver/CommonArgs.h" |
| 10 | #include "Arch/AArch64.h" |
| 11 | #include "Arch/ARM.h" |
| 12 | #include "Arch/CSKY.h" |
| 13 | #include "Arch/LoongArch.h" |
| 14 | #include "Arch/M68k.h" |
| 15 | #include "Arch/Mips.h" |
| 16 | #include "Arch/PPC.h" |
| 17 | #include "Arch/RISCV.h" |
| 18 | #include "Arch/Sparc.h" |
| 19 | #include "Arch/SystemZ.h" |
| 20 | #include "Arch/VE.h" |
| 21 | #include "Arch/X86.h" |
| 22 | #include "HIPAMD.h" |
| 23 | #include "Hexagon.h" |
| 24 | #include "MSP430.h" |
| 25 | #include "Solaris.h" |
| 26 | #include "ToolChains/Cuda.h" |
| 27 | #include "clang/Basic/CodeGenOptions.h" |
| 28 | #include "clang/Config/config.h" |
| 29 | #include "clang/Driver/Action.h" |
| 30 | #include "clang/Driver/Compilation.h" |
| 31 | #include "clang/Driver/Driver.h" |
| 32 | #include "clang/Driver/InputInfo.h" |
| 33 | #include "clang/Driver/Job.h" |
| 34 | #include "clang/Driver/SanitizerArgs.h" |
| 35 | #include "clang/Driver/ToolChain.h" |
| 36 | #include "clang/Driver/Util.h" |
| 37 | #include "clang/Driver/XRayArgs.h" |
| 38 | #include "clang/Frontend/CompilerInvocation.h" |
| 39 | #include "clang/Options/Options.h" |
| 40 | #include "llvm/ADT/STLExtras.h" |
| 41 | #include "llvm/ADT/SmallSet.h" |
| 42 | #include "llvm/ADT/SmallString.h" |
| 43 | #include "llvm/ADT/StringExtras.h" |
| 44 | #include "llvm/ADT/StringSwitch.h" |
| 45 | #include "llvm/ADT/Twine.h" |
| 46 | #include "llvm/BinaryFormat/Magic.h" |
| 47 | #include "llvm/Config/llvm-config.h" |
| 48 | #include "llvm/Option/Arg.h" |
| 49 | #include "llvm/Option/ArgList.h" |
| 50 | #include "llvm/Option/Option.h" |
| 51 | #include "llvm/Support/CodeGen.h" |
| 52 | #include "llvm/Support/Compression.h" |
| 53 | #include "llvm/Support/ErrorHandling.h" |
| 54 | #include "llvm/Support/FileSystem.h" |
| 55 | #include "llvm/Support/Path.h" |
| 56 | #include "llvm/Support/Process.h" |
| 57 | #include "llvm/Support/Program.h" |
| 58 | #include "llvm/Support/Threading.h" |
| 59 | #include "llvm/Support/VirtualFileSystem.h" |
| 60 | #include "llvm/Support/YAMLParser.h" |
| 61 | #include "llvm/TargetParser/Host.h" |
| 62 | #include "llvm/TargetParser/PPCTargetParser.h" |
| 63 | #include "llvm/TargetParser/TargetParser.h" |
| 64 | #include <optional> |
| 65 | |
| 66 | using namespace clang::driver; |
| 67 | using namespace clang::driver::tools; |
| 68 | using namespace clang; |
| 69 | using namespace llvm::opt; |
| 70 | |
| 71 | static bool useFramePointerForTargetByDefault(const llvm::opt::ArgList &Args, |
| 72 | const llvm::Triple &Triple) { |
| 73 | if (Args.hasArg(Ids: options::OPT_pg) && !Args.hasArg(Ids: options::OPT_mfentry)) |
| 74 | return true; |
| 75 | |
| 76 | if (Triple.isAndroid()) |
| 77 | return true; |
| 78 | |
| 79 | switch (Triple.getArch()) { |
| 80 | case llvm::Triple::xcore: |
| 81 | case llvm::Triple::wasm32: |
| 82 | case llvm::Triple::wasm64: |
| 83 | case llvm::Triple::msp430: |
| 84 | // XCore never wants frame pointers, regardless of OS. |
| 85 | // WebAssembly never wants frame pointers. |
| 86 | return false; |
| 87 | case llvm::Triple::ppc: |
| 88 | case llvm::Triple::ppcle: |
| 89 | case llvm::Triple::ppc64: |
| 90 | case llvm::Triple::ppc64le: |
| 91 | case llvm::Triple::riscv32: |
| 92 | case llvm::Triple::riscv64: |
| 93 | case llvm::Triple::sparc: |
| 94 | case llvm::Triple::sparcel: |
| 95 | case llvm::Triple::sparcv9: |
| 96 | case llvm::Triple::amdgcn: |
| 97 | case llvm::Triple::r600: |
| 98 | case llvm::Triple::csky: |
| 99 | case llvm::Triple::loongarch32: |
| 100 | case llvm::Triple::loongarch64: |
| 101 | case llvm::Triple::m68k: |
| 102 | return !clang::driver::tools::areOptimizationsEnabled(Args); |
| 103 | default: |
| 104 | break; |
| 105 | } |
| 106 | |
| 107 | if (Triple.isOSFuchsia() || Triple.isOSNetBSD()) { |
| 108 | return !clang::driver::tools::areOptimizationsEnabled(Args); |
| 109 | } |
| 110 | |
| 111 | if (Triple.isOSLinux() || Triple.isOSHurd()) { |
| 112 | switch (Triple.getArch()) { |
| 113 | // Don't use a frame pointer on linux if optimizing for certain targets. |
| 114 | case llvm::Triple::arm: |
| 115 | case llvm::Triple::armeb: |
| 116 | case llvm::Triple::thumb: |
| 117 | case llvm::Triple::thumbeb: |
| 118 | case llvm::Triple::mips64: |
| 119 | case llvm::Triple::mips64el: |
| 120 | case llvm::Triple::mips: |
| 121 | case llvm::Triple::mipsel: |
| 122 | case llvm::Triple::systemz: |
| 123 | case llvm::Triple::x86: |
| 124 | case llvm::Triple::x86_64: |
| 125 | return !clang::driver::tools::areOptimizationsEnabled(Args); |
| 126 | default: |
| 127 | return true; |
| 128 | } |
| 129 | } |
| 130 | |
| 131 | if (Triple.isOSWindows()) { |
| 132 | switch (Triple.getArch()) { |
| 133 | case llvm::Triple::x86: |
| 134 | return !clang::driver::tools::areOptimizationsEnabled(Args); |
| 135 | case llvm::Triple::x86_64: |
| 136 | return Triple.isOSBinFormatMachO(); |
| 137 | case llvm::Triple::arm: |
| 138 | case llvm::Triple::thumb: |
| 139 | // Windows on ARM builds with FPO disabled to aid fast stack walking |
| 140 | return true; |
| 141 | default: |
| 142 | // All other supported Windows ISAs use xdata unwind information, so frame |
| 143 | // pointers are not generally useful. |
| 144 | return false; |
| 145 | } |
| 146 | } |
| 147 | |
| 148 | if (arm::isARMEABIBareMetal(Triple)) |
| 149 | return false; |
| 150 | |
| 151 | return true; |
| 152 | } |
| 153 | |
| 154 | static bool useLeafFramePointerForTargetByDefault(const llvm::Triple &Triple) { |
| 155 | if (Triple.isAArch64() || Triple.isPS() || Triple.isVE() || |
| 156 | (Triple.isAndroid() && !Triple.isARM())) |
| 157 | return false; |
| 158 | |
| 159 | if ((Triple.isARM() || Triple.isThumb()) && Triple.isOSBinFormatMachO()) |
| 160 | return false; |
| 161 | |
| 162 | return true; |
| 163 | } |
| 164 | |
| 165 | static bool mustUseNonLeafFramePointerForTarget(const llvm::Triple &Triple) { |
| 166 | switch (Triple.getArch()) { |
| 167 | default: |
| 168 | return false; |
| 169 | case llvm::Triple::arm: |
| 170 | case llvm::Triple::thumb: |
| 171 | // ARM Darwin targets require a frame pointer to be always present to aid |
| 172 | // offline debugging via backtraces. |
| 173 | return Triple.isOSDarwin(); |
| 174 | } |
| 175 | } |
| 176 | |
| 177 | // True if a target-specific option requires the frame chain to be preserved, |
| 178 | // even if new frame records are not created. |
| 179 | static bool mustMaintainValidFrameChain(const llvm::opt::ArgList &Args, |
| 180 | const llvm::Triple &Triple) { |
| 181 | switch (Triple.getArch()) { |
| 182 | default: |
| 183 | return false; |
| 184 | case llvm::Triple::arm: |
| 185 | case llvm::Triple::armeb: |
| 186 | case llvm::Triple::thumb: |
| 187 | case llvm::Triple::thumbeb: |
| 188 | // For 32-bit Arm, the -mframe-chain=aapcs and -mframe-chain=aapcs+leaf |
| 189 | // options require the frame pointer register to be reserved (or point to a |
| 190 | // new AAPCS-compilant frame record), even with -fno-omit-frame-pointer. |
| 191 | if (Arg *A = Args.getLastArg(Ids: options::OPT_mframe_chain)) { |
| 192 | StringRef V = A->getValue(); |
| 193 | return V != "none" ; |
| 194 | } |
| 195 | return false; |
| 196 | |
| 197 | case llvm::Triple::aarch64: |
| 198 | // Arm64 Windows requires that the frame chain is valid, as there is no |
| 199 | // way to indicate during a stack walk that a frame has used the frame |
| 200 | // pointer as a general purpose register. |
| 201 | return Triple.isOSWindows(); |
| 202 | } |
| 203 | } |
| 204 | |
| 205 | // True if a target-specific option causes -fno-omit-frame-pointer to also |
| 206 | // cause frame records to be created in leaf functions. |
| 207 | static bool framePointerImpliesLeafFramePointer(const llvm::opt::ArgList &Args, |
| 208 | const llvm::Triple &Triple) { |
| 209 | if (Triple.isARM() || Triple.isThumb()) { |
| 210 | // For 32-bit Arm, the -mframe-chain=aapcs+leaf option causes the |
| 211 | // -fno-omit-frame-pointer optiion to imply -mno-omit-leaf-frame-pointer, |
| 212 | // but does not by itself imply either option. |
| 213 | if (Arg *A = Args.getLastArg(Ids: options::OPT_mframe_chain)) { |
| 214 | StringRef V = A->getValue(); |
| 215 | return V == "aapcs+leaf" ; |
| 216 | } |
| 217 | return false; |
| 218 | } |
| 219 | return false; |
| 220 | } |
| 221 | |
| 222 | clang::CodeGenOptions::FramePointerKind |
| 223 | getFramePointerKind(const llvm::opt::ArgList &Args, |
| 224 | const llvm::Triple &Triple) { |
| 225 | // There are four things to consider here: |
| 226 | // * Should a frame record be created for non-leaf functions? |
| 227 | // * Should a frame record be created for leaf functions? |
| 228 | // * Is the frame pointer register reserved in non-leaf functions? |
| 229 | // i.e. must it always point to either a new, valid frame record or be |
| 230 | // un-modified? |
| 231 | // * Is the frame pointer register reserved in leaf functions? |
| 232 | // |
| 233 | // Not all combinations of these are valid: |
| 234 | // * It's not useful to have leaf frame records without non-leaf ones. |
| 235 | // * It's not useful to have frame records without reserving the frame |
| 236 | // pointer. |
| 237 | // |
| 238 | // | Frame Setup | Reg Reserved | |
| 239 | // |-----------------|-----------------| |
| 240 | // | Non-leaf | Leaf | Non-Leaf | Leaf | |
| 241 | // |----------|------|----------|------| |
| 242 | // | N | N | N | N | FramePointerKind::None |
| 243 | // | N | N | N | Y | Invalid |
| 244 | // | N | N | Y | N | Invalid |
| 245 | // | N | N | Y | Y | FramePointerKind::Reserved |
| 246 | // | N | Y | N | N | Invalid |
| 247 | // | N | Y | N | Y | Invalid |
| 248 | // | N | Y | Y | N | Invalid |
| 249 | // | N | Y | Y | Y | Invalid |
| 250 | // | Y | N | N | N | Invalid |
| 251 | // | Y | N | N | Y | Invalid |
| 252 | // | Y | N | Y | N | FramePointerKind::NonLeafNoReserve |
| 253 | // | Y | N | Y | Y | FramePointerKind::NonLeaf |
| 254 | // | Y | Y | N | N | Invalid |
| 255 | // | Y | Y | N | Y | Invalid |
| 256 | // | Y | Y | Y | N | Invalid |
| 257 | // | Y | Y | Y | Y | FramePointerKind::All |
| 258 | // |
| 259 | // The FramePointerKind::Reserved case is currently only reachable for Arm, |
| 260 | // which has the -mframe-chain= option which can (in combination with |
| 261 | // -fno-omit-frame-pointer) specify that the frame chain must be valid, |
| 262 | // without requiring new frame records to be created. |
| 263 | |
| 264 | bool DefaultFP = useFramePointerForTargetByDefault(Args, Triple); |
| 265 | bool EnableFP = mustUseNonLeafFramePointerForTarget(Triple) || |
| 266 | Args.hasFlag(Pos: options::OPT_fno_omit_frame_pointer, |
| 267 | Neg: options::OPT_fomit_frame_pointer, Default: DefaultFP); |
| 268 | |
| 269 | bool DefaultLeafFP = |
| 270 | useLeafFramePointerForTargetByDefault(Triple) || |
| 271 | (EnableFP && framePointerImpliesLeafFramePointer(Args, Triple)); |
| 272 | bool EnableLeafFP = |
| 273 | Args.hasFlag(Pos: options::OPT_mno_omit_leaf_frame_pointer, |
| 274 | Neg: options::OPT_momit_leaf_frame_pointer, Default: DefaultLeafFP); |
| 275 | |
| 276 | bool FPRegReserved = Args.hasFlag(Pos: options::OPT_mreserve_frame_pointer_reg, |
| 277 | Neg: options::OPT_mno_reserve_frame_pointer_reg, |
| 278 | Default: mustMaintainValidFrameChain(Args, Triple)); |
| 279 | |
| 280 | if (EnableFP) { |
| 281 | if (EnableLeafFP) |
| 282 | return clang::CodeGenOptions::FramePointerKind::All; |
| 283 | |
| 284 | if (FPRegReserved) |
| 285 | return clang::CodeGenOptions::FramePointerKind::NonLeaf; |
| 286 | |
| 287 | return clang::CodeGenOptions::FramePointerKind::NonLeafNoReserve; |
| 288 | } |
| 289 | if (FPRegReserved) |
| 290 | return clang::CodeGenOptions::FramePointerKind::Reserved; |
| 291 | return clang::CodeGenOptions::FramePointerKind::None; |
| 292 | } |
| 293 | |
| 294 | static void renderRpassOptions(const ArgList &Args, ArgStringList &CmdArgs, |
| 295 | const StringRef PluginOptPrefix) { |
| 296 | if (const Arg *A = Args.getLastArg(Ids: options::OPT_Rpass_EQ)) |
| 297 | CmdArgs.push_back(Elt: Args.MakeArgString(Str: Twine(PluginOptPrefix) + |
| 298 | "-pass-remarks=" + A->getValue())); |
| 299 | |
| 300 | if (const Arg *A = Args.getLastArg(Ids: options::OPT_Rpass_missed_EQ)) |
| 301 | CmdArgs.push_back(Elt: Args.MakeArgString( |
| 302 | Str: Twine(PluginOptPrefix) + "-pass-remarks-missed=" + A->getValue())); |
| 303 | |
| 304 | if (const Arg *A = Args.getLastArg(Ids: options::OPT_Rpass_analysis_EQ)) |
| 305 | CmdArgs.push_back(Elt: Args.MakeArgString( |
| 306 | Str: Twine(PluginOptPrefix) + "-pass-remarks-analysis=" + A->getValue())); |
| 307 | } |
| 308 | |
| 309 | static void (const ArgList &Args, ArgStringList &CmdArgs, |
| 310 | const llvm::Triple &Triple, |
| 311 | const InputInfo &Input, |
| 312 | const InputInfo &Output, |
| 313 | const StringRef PluginOptPrefix) { |
| 314 | StringRef Format = "yaml" ; |
| 315 | if (const Arg *A = Args.getLastArg(Ids: options::OPT_fsave_optimization_record_EQ)) |
| 316 | Format = A->getValue(); |
| 317 | |
| 318 | SmallString<128> F; |
| 319 | if (const Arg *A = |
| 320 | Args.getLastArg(Ids: options::OPT_foptimization_record_file_EQ)) { |
| 321 | F = A->getValue(); |
| 322 | F += "." ; |
| 323 | } else if (const Arg *A = Args.getLastArg(Ids: options::OPT_dumpdir)) { |
| 324 | F = A->getValue(); |
| 325 | } else if (Output.isFilename()) { |
| 326 | F = Output.getFilename(); |
| 327 | F += "." ; |
| 328 | } |
| 329 | |
| 330 | assert(!F.empty() && "Cannot determine remarks output name." ); |
| 331 | // Append "opt.ld.<format>" to the end of the file name. |
| 332 | CmdArgs.push_back(Elt: Args.MakeArgString(Str: Twine(PluginOptPrefix) + |
| 333 | "opt-remarks-filename=" + F + "opt.ld." + |
| 334 | Format)); |
| 335 | |
| 336 | if (const Arg *A = |
| 337 | Args.getLastArg(Ids: options::OPT_foptimization_record_passes_EQ)) |
| 338 | CmdArgs.push_back(Elt: Args.MakeArgString( |
| 339 | Str: Twine(PluginOptPrefix) + "opt-remarks-passes=" + A->getValue())); |
| 340 | |
| 341 | CmdArgs.push_back(Elt: Args.MakeArgString(Str: Twine(PluginOptPrefix) + |
| 342 | "opt-remarks-format=" + Format.data())); |
| 343 | } |
| 344 | |
| 345 | static void (const ArgList &Args, |
| 346 | ArgStringList &CmdArgs, |
| 347 | const StringRef PluginOptPrefix) { |
| 348 | if (Args.hasFlag(Pos: options::OPT_fdiagnostics_show_hotness, |
| 349 | Neg: options::OPT_fno_diagnostics_show_hotness, Default: false)) |
| 350 | CmdArgs.push_back(Elt: Args.MakeArgString(Str: Twine(PluginOptPrefix) + |
| 351 | "opt-remarks-with-hotness" )); |
| 352 | |
| 353 | if (const Arg *A = |
| 354 | Args.getLastArg(Ids: options::OPT_fdiagnostics_hotness_threshold_EQ)) |
| 355 | CmdArgs.push_back( |
| 356 | Elt: Args.MakeArgString(Str: Twine(PluginOptPrefix) + |
| 357 | "opt-remarks-hotness-threshold=" + A->getValue())); |
| 358 | } |
| 359 | |
| 360 | static bool shouldIgnoreUnsupportedTargetFeature(const Arg &TargetFeatureArg, |
| 361 | llvm::Triple T, |
| 362 | StringRef Processor) { |
| 363 | // Warn no-cumode for AMDGCN processors not supporing WGP mode. |
| 364 | if (!T.isAMDGPU()) |
| 365 | return false; |
| 366 | auto GPUKind = T.isAMDGCN() ? llvm::AMDGPU::parseArchAMDGCN(CPU: Processor) |
| 367 | : llvm::AMDGPU::parseArchR600(CPU: Processor); |
| 368 | auto GPUFeatures = T.isAMDGCN() ? llvm::AMDGPU::getArchAttrAMDGCN(AK: GPUKind) |
| 369 | : llvm::AMDGPU::getArchAttrR600(AK: GPUKind); |
| 370 | if (GPUFeatures & llvm::AMDGPU::FEATURE_WGP) |
| 371 | return false; |
| 372 | return TargetFeatureArg.getOption().matches(ID: options::OPT_mno_cumode); |
| 373 | } |
| 374 | |
| 375 | void tools::addPathIfExists(const Driver &D, const Twine &Path, |
| 376 | ToolChain::path_list &Paths) { |
| 377 | if (D.getVFS().exists(Path)) |
| 378 | Paths.push_back(Elt: Path.str()); |
| 379 | } |
| 380 | |
| 381 | void tools::handleTargetFeaturesGroup(const Driver &D, |
| 382 | const llvm::Triple &Triple, |
| 383 | const ArgList &Args, |
| 384 | std::vector<StringRef> &Features, |
| 385 | OptSpecifier Group) { |
| 386 | std::set<StringRef> Warned; |
| 387 | for (const Arg *A : Args.filtered(Ids: Group)) { |
| 388 | StringRef Name = A->getOption().getName(); |
| 389 | A->claim(); |
| 390 | |
| 391 | // Skip over "-m". |
| 392 | assert(Name.starts_with("m" ) && "Invalid feature name." ); |
| 393 | Name = Name.substr(Start: 1); |
| 394 | |
| 395 | auto Proc = getCPUName(D, Args, T: Triple); |
| 396 | if (shouldIgnoreUnsupportedTargetFeature(TargetFeatureArg: *A, T: Triple, Processor: Proc)) { |
| 397 | if (Warned.count(x: Name) == 0) { |
| 398 | D.getDiags().Report( |
| 399 | DiagID: clang::diag::warn_drv_unsupported_option_for_processor) |
| 400 | << A->getAsString(Args) << Proc; |
| 401 | Warned.insert(x: Name); |
| 402 | } |
| 403 | continue; |
| 404 | } |
| 405 | |
| 406 | bool IsNegative = Name.consume_front(Prefix: "no-" ); |
| 407 | |
| 408 | Features.push_back(x: Args.MakeArgString(Str: (IsNegative ? "-" : "+" ) + Name)); |
| 409 | } |
| 410 | } |
| 411 | |
| 412 | SmallVector<StringRef> |
| 413 | tools::unifyTargetFeatures(ArrayRef<StringRef> Features) { |
| 414 | // Only add a feature if it hasn't been seen before starting from the end. |
| 415 | SmallVector<StringRef> UnifiedFeatures; |
| 416 | llvm::DenseSet<StringRef> UsedFeatures; |
| 417 | for (StringRef Feature : llvm::reverse(C&: Features)) { |
| 418 | if (UsedFeatures.insert(V: Feature.drop_front()).second) |
| 419 | UnifiedFeatures.insert(I: UnifiedFeatures.begin(), Elt: Feature); |
| 420 | } |
| 421 | |
| 422 | return UnifiedFeatures; |
| 423 | } |
| 424 | |
| 425 | void tools::addDirectoryList(const ArgList &Args, ArgStringList &CmdArgs, |
| 426 | const char *ArgName, const char *EnvVar) { |
| 427 | const char *DirList = ::getenv(name: EnvVar); |
| 428 | bool CombinedArg = false; |
| 429 | |
| 430 | if (!DirList) |
| 431 | return; // Nothing to do. |
| 432 | |
| 433 | StringRef Name(ArgName); |
| 434 | if (Name == "-I" || Name == "-L" || Name.empty()) |
| 435 | CombinedArg = true; |
| 436 | |
| 437 | StringRef Dirs(DirList); |
| 438 | if (Dirs.empty()) // Empty string should not add '.'. |
| 439 | return; |
| 440 | |
| 441 | StringRef::size_type Delim; |
| 442 | while ((Delim = Dirs.find(C: llvm::sys::EnvPathSeparator)) != StringRef::npos) { |
| 443 | if (Delim == 0) { // Leading colon. |
| 444 | if (CombinedArg) { |
| 445 | CmdArgs.push_back(Elt: Args.MakeArgString(Str: std::string(ArgName) + "." )); |
| 446 | } else { |
| 447 | CmdArgs.push_back(Elt: ArgName); |
| 448 | CmdArgs.push_back(Elt: "." ); |
| 449 | } |
| 450 | } else { |
| 451 | if (CombinedArg) { |
| 452 | CmdArgs.push_back( |
| 453 | Elt: Args.MakeArgString(Str: std::string(ArgName) + Dirs.substr(Start: 0, N: Delim))); |
| 454 | } else { |
| 455 | CmdArgs.push_back(Elt: ArgName); |
| 456 | CmdArgs.push_back(Elt: Args.MakeArgString(Str: Dirs.substr(Start: 0, N: Delim))); |
| 457 | } |
| 458 | } |
| 459 | Dirs = Dirs.substr(Start: Delim + 1); |
| 460 | } |
| 461 | |
| 462 | if (Dirs.empty()) { // Trailing colon. |
| 463 | if (CombinedArg) { |
| 464 | CmdArgs.push_back(Elt: Args.MakeArgString(Str: std::string(ArgName) + "." )); |
| 465 | } else { |
| 466 | CmdArgs.push_back(Elt: ArgName); |
| 467 | CmdArgs.push_back(Elt: "." ); |
| 468 | } |
| 469 | } else { // Add the last path. |
| 470 | if (CombinedArg) { |
| 471 | CmdArgs.push_back(Elt: Args.MakeArgString(Str: std::string(ArgName) + Dirs)); |
| 472 | } else { |
| 473 | CmdArgs.push_back(Elt: ArgName); |
| 474 | CmdArgs.push_back(Elt: Args.MakeArgString(Str: Dirs)); |
| 475 | } |
| 476 | } |
| 477 | } |
| 478 | |
| 479 | void tools::AddLinkerInputs(const ToolChain &TC, const InputInfoList &Inputs, |
| 480 | const ArgList &Args, ArgStringList &CmdArgs, |
| 481 | const JobAction &JA) { |
| 482 | const Driver &D = TC.getDriver(); |
| 483 | |
| 484 | // Add extra linker input arguments which are not treated as inputs |
| 485 | // (constructed via -Xarch_). |
| 486 | Args.AddAllArgValues(Output&: CmdArgs, Id0: options::OPT_Zlinker_input); |
| 487 | |
| 488 | // LIBRARY_PATH are included before user inputs and only supported on native |
| 489 | // toolchains. |
| 490 | if (!TC.isCrossCompiling()) |
| 491 | addDirectoryList(Args, CmdArgs, ArgName: "-L" , EnvVar: "LIBRARY_PATH" ); |
| 492 | |
| 493 | for (const auto &II : Inputs) { |
| 494 | // If the current tool chain refers to an OpenMP offloading host, we |
| 495 | // should ignore inputs that refer to OpenMP offloading devices - |
| 496 | // they will be embedded according to a proper linker script. |
| 497 | if (auto *IA = II.getAction()) |
| 498 | if ((JA.isHostOffloading(OKind: Action::OFK_OpenMP) && |
| 499 | IA->isDeviceOffloading(OKind: Action::OFK_OpenMP))) |
| 500 | continue; |
| 501 | |
| 502 | if (!TC.HasNativeLLVMSupport() && types::isLLVMIR(Id: II.getType())) |
| 503 | // Don't try to pass LLVM inputs unless we have native support. |
| 504 | D.Diag(DiagID: diag::err_drv_no_linker_llvm_support) << TC.getTripleString(); |
| 505 | |
| 506 | // Add filenames immediately. |
| 507 | if (II.isFilename()) { |
| 508 | CmdArgs.push_back(Elt: II.getFilename()); |
| 509 | continue; |
| 510 | } |
| 511 | |
| 512 | // In some error cases, the input could be Nothing; skip those. |
| 513 | if (II.isNothing()) |
| 514 | continue; |
| 515 | |
| 516 | // Otherwise, this is a linker input argument. |
| 517 | const Arg &A = II.getInputArg(); |
| 518 | |
| 519 | // Handle reserved library options. |
| 520 | if (A.getOption().matches(ID: options::OPT_Z_reserved_lib_stdcxx)) |
| 521 | TC.AddCXXStdlibLibArgs(Args, CmdArgs); |
| 522 | else if (A.getOption().matches(ID: options::OPT_Z_reserved_lib_cckext)) |
| 523 | TC.AddCCKextLibArgs(Args, CmdArgs); |
| 524 | // Do not pass OPT_rpath to linker in AIX |
| 525 | else if (A.getOption().matches(ID: options::OPT_rpath) && |
| 526 | TC.getTriple().isOSAIX()) |
| 527 | continue; |
| 528 | else |
| 529 | A.renderAsInput(Args, Output&: CmdArgs); |
| 530 | } |
| 531 | if (const Arg *A = Args.getLastArg(Ids: options::OPT_fveclib)) { |
| 532 | const llvm::Triple &Triple = TC.getTriple(); |
| 533 | StringRef V = A->getValue(); |
| 534 | if (V == "ArmPL" && (Triple.isOSLinux() || Triple.isOSDarwin())) { |
| 535 | // To support -fveclib=ArmPL we need to link against libamath. Some of the |
| 536 | // libamath functions depend on libm, at the same time, libamath exports |
| 537 | // its own implementation of some of the libm functions. These are faster |
| 538 | // and potentially less accurate implementations, hence we need to be |
| 539 | // careful what is being linked in. Since here we are interested only in |
| 540 | // the subset of libamath functions that is covered by the veclib |
| 541 | // mappings, we need to prioritize libm functions by putting -lm before |
| 542 | // -lamath (and then -lm again, to fulfill libamath requirements). |
| 543 | // |
| 544 | // Therefore we need to do the following: |
| 545 | // |
| 546 | // 1. On Linux, link only when actually needed. |
| 547 | // |
| 548 | // 2. Prefer libm functions over libamath (when no -nostdlib in use). |
| 549 | // |
| 550 | // 3. Link against libm to resolve libamath dependencies. |
| 551 | // |
| 552 | if (Triple.isOSLinux()) { |
| 553 | CmdArgs.push_back(Elt: Args.MakeArgString(Str: "--push-state" )); |
| 554 | CmdArgs.push_back(Elt: Args.MakeArgString(Str: "--as-needed" )); |
| 555 | } |
| 556 | if (!Args.hasArg(Ids: options::OPT_nostdlib)) |
| 557 | CmdArgs.push_back(Elt: Args.MakeArgString(Str: "-lm" )); |
| 558 | CmdArgs.push_back(Elt: Args.MakeArgString(Str: "-lamath" )); |
| 559 | if (!Args.hasArg(Ids: options::OPT_nostdlib)) |
| 560 | CmdArgs.push_back(Elt: Args.MakeArgString(Str: "-lm" )); |
| 561 | if (Triple.isOSLinux()) |
| 562 | CmdArgs.push_back(Elt: Args.MakeArgString(Str: "--pop-state" )); |
| 563 | addArchSpecificRPath(TC, Args, CmdArgs); |
| 564 | } |
| 565 | } |
| 566 | } |
| 567 | |
| 568 | const char *tools::getLDMOption(const llvm::Triple &T, const ArgList &Args) { |
| 569 | switch (T.getArch()) { |
| 570 | case llvm::Triple::x86: |
| 571 | if (T.isOSIAMCU()) |
| 572 | return "elf_iamcu" ; |
| 573 | return "elf_i386" ; |
| 574 | case llvm::Triple::aarch64: |
| 575 | if (T.isOSManagarm()) |
| 576 | return "aarch64managarm" ; |
| 577 | else if (aarch64::isAArch64BareMetal(Triple: T)) |
| 578 | return "aarch64elf" ; |
| 579 | return "aarch64linux" ; |
| 580 | case llvm::Triple::aarch64_be: |
| 581 | if (aarch64::isAArch64BareMetal(Triple: T)) |
| 582 | return "aarch64elfb" ; |
| 583 | return "aarch64linuxb" ; |
| 584 | case llvm::Triple::arm: |
| 585 | case llvm::Triple::thumb: |
| 586 | case llvm::Triple::armeb: |
| 587 | case llvm::Triple::thumbeb: { |
| 588 | bool IsBigEndian = tools::arm::isARMBigEndian(Triple: T, Args); |
| 589 | if (arm::isARMEABIBareMetal(Triple: T)) |
| 590 | return IsBigEndian ? "armelfb" : "armelf" ; |
| 591 | return IsBigEndian ? "armelfb_linux_eabi" : "armelf_linux_eabi" ; |
| 592 | } |
| 593 | case llvm::Triple::m68k: |
| 594 | return "m68kelf" ; |
| 595 | case llvm::Triple::ppc: |
| 596 | if (T.isOSLinux()) |
| 597 | return "elf32ppclinux" ; |
| 598 | return "elf32ppc" ; |
| 599 | case llvm::Triple::ppcle: |
| 600 | if (T.isOSLinux()) |
| 601 | return "elf32lppclinux" ; |
| 602 | return "elf32lppc" ; |
| 603 | case llvm::Triple::ppc64: |
| 604 | return "elf64ppc" ; |
| 605 | case llvm::Triple::ppc64le: |
| 606 | return "elf64lppc" ; |
| 607 | case llvm::Triple::riscv32: |
| 608 | return "elf32lriscv" ; |
| 609 | case llvm::Triple::riscv64: |
| 610 | return "elf64lriscv" ; |
| 611 | case llvm::Triple::sparc: |
| 612 | case llvm::Triple::sparcel: |
| 613 | return "elf32_sparc" ; |
| 614 | case llvm::Triple::sparcv9: |
| 615 | return "elf64_sparc" ; |
| 616 | case llvm::Triple::loongarch32: |
| 617 | return "elf32loongarch" ; |
| 618 | case llvm::Triple::loongarch64: |
| 619 | return "elf64loongarch" ; |
| 620 | case llvm::Triple::mips: |
| 621 | return "elf32btsmip" ; |
| 622 | case llvm::Triple::mipsel: |
| 623 | return "elf32ltsmip" ; |
| 624 | case llvm::Triple::mips64: |
| 625 | if (tools::mips::hasMipsAbiArg(Args, Value: "n32" ) || T.isABIN32()) |
| 626 | return "elf32btsmipn32" ; |
| 627 | return "elf64btsmip" ; |
| 628 | case llvm::Triple::mips64el: |
| 629 | if (tools::mips::hasMipsAbiArg(Args, Value: "n32" ) || T.isABIN32()) |
| 630 | return "elf32ltsmipn32" ; |
| 631 | return "elf64ltsmip" ; |
| 632 | case llvm::Triple::systemz: |
| 633 | return "elf64_s390" ; |
| 634 | case llvm::Triple::x86_64: |
| 635 | if (T.isX32()) |
| 636 | return "elf32_x86_64" ; |
| 637 | return "elf_x86_64" ; |
| 638 | case llvm::Triple::ve: |
| 639 | return "elf64ve" ; |
| 640 | case llvm::Triple::csky: |
| 641 | return "cskyelf_linux" ; |
| 642 | default: |
| 643 | return nullptr; |
| 644 | } |
| 645 | } |
| 646 | |
| 647 | void tools::addLinkerCompressDebugSectionsOption( |
| 648 | const ToolChain &TC, const llvm::opt::ArgList &Args, |
| 649 | llvm::opt::ArgStringList &CmdArgs) { |
| 650 | // GNU ld supports --compress-debug-sections=none|zlib|zlib-gnu|zlib-gabi |
| 651 | // whereas zlib is an alias to zlib-gabi and zlib-gnu is obsoleted. Therefore |
| 652 | // -gz=none|zlib are translated to --compress-debug-sections=none|zlib. -gz |
| 653 | // is not translated since ld --compress-debug-sections option requires an |
| 654 | // argument. |
| 655 | if (const Arg *A = Args.getLastArg(Ids: options::OPT_gz_EQ)) { |
| 656 | StringRef V = A->getValue(); |
| 657 | if (V == "none" || V == "zlib" || V == "zstd" ) |
| 658 | CmdArgs.push_back(Elt: Args.MakeArgString(Str: "--compress-debug-sections=" + V)); |
| 659 | else |
| 660 | TC.getDriver().Diag(DiagID: diag::err_drv_unsupported_option_argument) |
| 661 | << A->getSpelling() << V; |
| 662 | } |
| 663 | } |
| 664 | |
| 665 | void tools::AddTargetFeature(const ArgList &Args, |
| 666 | std::vector<StringRef> &Features, |
| 667 | OptSpecifier OnOpt, OptSpecifier OffOpt, |
| 668 | StringRef FeatureName) { |
| 669 | if (Arg *A = Args.getLastArg(Ids: OnOpt, Ids: OffOpt)) { |
| 670 | if (A->getOption().matches(ID: OnOpt)) |
| 671 | Features.push_back(x: Args.MakeArgString(Str: "+" + FeatureName)); |
| 672 | else |
| 673 | Features.push_back(x: Args.MakeArgString(Str: "-" + FeatureName)); |
| 674 | } |
| 675 | } |
| 676 | |
| 677 | /// Get the (LLVM) name of the AMDGPU gpu we are targeting. |
| 678 | static std::string getAMDGPUTargetGPU(const llvm::Triple &T, |
| 679 | const ArgList &Args) { |
| 680 | Arg *MArch = Args.getLastArg(Ids: options::OPT_march_EQ); |
| 681 | if (Arg *A = Args.getLastArg(Ids: options::OPT_mcpu_EQ)) { |
| 682 | auto GPUName = getProcessorFromTargetID(T, OffloadArch: A->getValue()); |
| 683 | return llvm::StringSwitch<std::string>(GPUName) |
| 684 | .Cases(CaseStrings: {"rv630" , "rv635" }, Value: "r600" ) |
| 685 | .Cases(CaseStrings: {"rv610" , "rv620" , "rs780" }, Value: "rs880" ) |
| 686 | .Case(S: "rv740" , Value: "rv770" ) |
| 687 | .Case(S: "palm" , Value: "cedar" ) |
| 688 | .Cases(CaseStrings: {"sumo" , "sumo2" }, Value: "sumo" ) |
| 689 | .Case(S: "hemlock" , Value: "cypress" ) |
| 690 | .Case(S: "aruba" , Value: "cayman" ) |
| 691 | .Default(Value: GPUName.str()); |
| 692 | } |
| 693 | if (MArch) |
| 694 | return getProcessorFromTargetID(T, OffloadArch: MArch->getValue()).str(); |
| 695 | return "" ; |
| 696 | } |
| 697 | |
| 698 | static std::string getLanaiTargetCPU(const ArgList &Args) { |
| 699 | if (Arg *A = Args.getLastArg(Ids: options::OPT_mcpu_EQ)) { |
| 700 | return A->getValue(); |
| 701 | } |
| 702 | return "" ; |
| 703 | } |
| 704 | |
| 705 | /// Get the (LLVM) name of the WebAssembly cpu we are targeting. |
| 706 | static StringRef getWebAssemblyTargetCPU(const ArgList &Args) { |
| 707 | // If we have -mcpu=, use that. |
| 708 | if (Arg *A = Args.getLastArg(Ids: options::OPT_mcpu_EQ)) { |
| 709 | StringRef CPU = A->getValue(); |
| 710 | |
| 711 | #ifdef __wasm__ |
| 712 | // Handle "native" by examining the host. "native" isn't meaningful when |
| 713 | // cross compiling, so only support this when the host is also WebAssembly. |
| 714 | if (CPU == "native" ) |
| 715 | return llvm::sys::getHostCPUName(); |
| 716 | #endif |
| 717 | |
| 718 | return CPU; |
| 719 | } |
| 720 | |
| 721 | return "generic" ; |
| 722 | } |
| 723 | |
| 724 | std::string tools::getCPUName(const Driver &D, const ArgList &Args, |
| 725 | const llvm::Triple &T, bool FromAs) { |
| 726 | Arg *A; |
| 727 | |
| 728 | switch (T.getArch()) { |
| 729 | default: |
| 730 | return "" ; |
| 731 | |
| 732 | case llvm::Triple::aarch64: |
| 733 | case llvm::Triple::aarch64_32: |
| 734 | case llvm::Triple::aarch64_be: |
| 735 | return aarch64::getAArch64TargetCPU(Args, Triple: T, A); |
| 736 | |
| 737 | case llvm::Triple::arm: |
| 738 | case llvm::Triple::armeb: |
| 739 | case llvm::Triple::thumb: |
| 740 | case llvm::Triple::thumbeb: { |
| 741 | StringRef MArch, MCPU; |
| 742 | arm::getARMArchCPUFromArgs(Args, Arch&: MArch, CPU&: MCPU, FromAs); |
| 743 | return arm::getARMTargetCPU(CPU: MCPU, Arch: MArch, Triple: T); |
| 744 | } |
| 745 | |
| 746 | case llvm::Triple::avr: |
| 747 | if (const Arg *A = Args.getLastArg(Ids: options::OPT_mmcu_EQ)) |
| 748 | return A->getValue(); |
| 749 | return "" ; |
| 750 | |
| 751 | case llvm::Triple::m68k: |
| 752 | return m68k::getM68kTargetCPU(Args); |
| 753 | |
| 754 | case llvm::Triple::mips: |
| 755 | case llvm::Triple::mipsel: |
| 756 | case llvm::Triple::mips64: |
| 757 | case llvm::Triple::mips64el: { |
| 758 | StringRef CPUName; |
| 759 | StringRef ABIName; |
| 760 | mips::getMipsCPUAndABI(Args, Triple: T, CPUName, ABIName); |
| 761 | return std::string(CPUName); |
| 762 | } |
| 763 | |
| 764 | case llvm::Triple::nvptx: |
| 765 | case llvm::Triple::nvptx64: |
| 766 | if (const Arg *A = Args.getLastArg(Ids: options::OPT_march_EQ)) |
| 767 | return A->getValue(); |
| 768 | return "" ; |
| 769 | |
| 770 | case llvm::Triple::ppc: |
| 771 | case llvm::Triple::ppcle: |
| 772 | case llvm::Triple::ppc64: |
| 773 | case llvm::Triple::ppc64le: |
| 774 | if (Arg *A = Args.getLastArg(Ids: options::OPT_mcpu_EQ)) |
| 775 | return std::string( |
| 776 | llvm::PPC::getNormalizedPPCTargetCPU(T, CPUName: A->getValue())); |
| 777 | return std::string(llvm::PPC::getNormalizedPPCTargetCPU(T)); |
| 778 | |
| 779 | case llvm::Triple::csky: |
| 780 | if (const Arg *A = Args.getLastArg(Ids: options::OPT_mcpu_EQ)) |
| 781 | return A->getValue(); |
| 782 | else if (const Arg *A = Args.getLastArg(Ids: options::OPT_march_EQ)) |
| 783 | return A->getValue(); |
| 784 | else |
| 785 | return "ck810" ; |
| 786 | case llvm::Triple::riscv32: |
| 787 | case llvm::Triple::riscv64: |
| 788 | return riscv::getRISCVTargetCPU(Args, Triple: T); |
| 789 | |
| 790 | case llvm::Triple::bpfel: |
| 791 | case llvm::Triple::bpfeb: |
| 792 | if (const Arg *A = Args.getLastArg(Ids: options::OPT_mcpu_EQ)) |
| 793 | return A->getValue(); |
| 794 | return "" ; |
| 795 | |
| 796 | case llvm::Triple::sparc: |
| 797 | case llvm::Triple::sparcel: |
| 798 | case llvm::Triple::sparcv9: |
| 799 | return sparc::getSparcTargetCPU(D, Args, Triple: T); |
| 800 | |
| 801 | case llvm::Triple::x86: |
| 802 | case llvm::Triple::x86_64: |
| 803 | return x86::getX86TargetCPU(D, Args, Triple: T); |
| 804 | |
| 805 | case llvm::Triple::hexagon: |
| 806 | return "hexagon" + |
| 807 | toolchains::HexagonToolChain::GetTargetCPUVersion(Args).str(); |
| 808 | |
| 809 | case llvm::Triple::lanai: |
| 810 | return getLanaiTargetCPU(Args); |
| 811 | |
| 812 | case llvm::Triple::systemz: |
| 813 | return systemz::getSystemZTargetCPU(Args, T); |
| 814 | |
| 815 | case llvm::Triple::r600: |
| 816 | case llvm::Triple::amdgcn: |
| 817 | return getAMDGPUTargetGPU(T, Args); |
| 818 | |
| 819 | case llvm::Triple::wasm32: |
| 820 | case llvm::Triple::wasm64: |
| 821 | return std::string(getWebAssemblyTargetCPU(Args)); |
| 822 | |
| 823 | case llvm::Triple::loongarch32: |
| 824 | case llvm::Triple::loongarch64: |
| 825 | return loongarch::getLoongArchTargetCPU(Args, Triple: T); |
| 826 | |
| 827 | case llvm::Triple::xtensa: |
| 828 | if (const Arg *A = Args.getLastArg(Ids: options::OPT_mcpu_EQ)) |
| 829 | return A->getValue(); |
| 830 | return "" ; |
| 831 | } |
| 832 | } |
| 833 | |
| 834 | static void getWebAssemblyTargetFeatures(const Driver &D, |
| 835 | const llvm::Triple &Triple, |
| 836 | const ArgList &Args, |
| 837 | std::vector<StringRef> &Features) { |
| 838 | handleTargetFeaturesGroup(D, Triple, Args, Features, |
| 839 | Group: options::OPT_m_wasm_Features_Group); |
| 840 | } |
| 841 | |
| 842 | void tools::getTargetFeatures(const Driver &D, const llvm::Triple &Triple, |
| 843 | const ArgList &Args, ArgStringList &CmdArgs, |
| 844 | bool ForAS, bool IsAux) { |
| 845 | std::vector<StringRef> Features; |
| 846 | switch (Triple.getArch()) { |
| 847 | default: |
| 848 | break; |
| 849 | case llvm::Triple::mips: |
| 850 | case llvm::Triple::mipsel: |
| 851 | case llvm::Triple::mips64: |
| 852 | case llvm::Triple::mips64el: |
| 853 | mips::getMIPSTargetFeatures(D, Triple, Args, Features); |
| 854 | break; |
| 855 | case llvm::Triple::arm: |
| 856 | case llvm::Triple::armeb: |
| 857 | case llvm::Triple::thumb: |
| 858 | case llvm::Triple::thumbeb: |
| 859 | arm::getARMTargetFeatures(D, Triple, Args, Features, ForAS); |
| 860 | break; |
| 861 | case llvm::Triple::ppc: |
| 862 | case llvm::Triple::ppcle: |
| 863 | case llvm::Triple::ppc64: |
| 864 | case llvm::Triple::ppc64le: |
| 865 | ppc::getPPCTargetFeatures(D, Triple, Args, Features); |
| 866 | break; |
| 867 | case llvm::Triple::riscv32: |
| 868 | case llvm::Triple::riscv64: |
| 869 | riscv::getRISCVTargetFeatures(D, Triple, Args, Features); |
| 870 | break; |
| 871 | case llvm::Triple::systemz: |
| 872 | systemz::getSystemZTargetFeatures(D, Args, Features); |
| 873 | break; |
| 874 | case llvm::Triple::aarch64: |
| 875 | case llvm::Triple::aarch64_32: |
| 876 | case llvm::Triple::aarch64_be: |
| 877 | aarch64::getAArch64TargetFeatures(D, Triple, Args, Features, ForAS); |
| 878 | break; |
| 879 | case llvm::Triple::x86: |
| 880 | case llvm::Triple::x86_64: |
| 881 | x86::getX86TargetFeatures(D, Triple, Args, Features); |
| 882 | break; |
| 883 | case llvm::Triple::hexagon: |
| 884 | hexagon::getHexagonTargetFeatures(D, Triple, Args, Features); |
| 885 | break; |
| 886 | case llvm::Triple::wasm32: |
| 887 | case llvm::Triple::wasm64: |
| 888 | getWebAssemblyTargetFeatures(D, Triple, Args, Features); |
| 889 | break; |
| 890 | case llvm::Triple::sparc: |
| 891 | case llvm::Triple::sparcel: |
| 892 | case llvm::Triple::sparcv9: |
| 893 | sparc::getSparcTargetFeatures(D, Triple, Args, Features); |
| 894 | break; |
| 895 | case llvm::Triple::r600: |
| 896 | case llvm::Triple::amdgcn: |
| 897 | amdgpu::getAMDGPUTargetFeatures(D, Triple, Args, Features); |
| 898 | break; |
| 899 | case llvm::Triple::nvptx: |
| 900 | case llvm::Triple::nvptx64: |
| 901 | NVPTX::getNVPTXTargetFeatures(D, Triple, Args, Features); |
| 902 | break; |
| 903 | case llvm::Triple::m68k: |
| 904 | m68k::getM68kTargetFeatures(D, Triple, Args, Features); |
| 905 | break; |
| 906 | case llvm::Triple::msp430: |
| 907 | msp430::getMSP430TargetFeatures(D, Args, Features); |
| 908 | break; |
| 909 | case llvm::Triple::ve: |
| 910 | ve::getVETargetFeatures(D, Args, Features); |
| 911 | break; |
| 912 | case llvm::Triple::csky: |
| 913 | csky::getCSKYTargetFeatures(D, Triple, Args, CmdArgs, Features); |
| 914 | break; |
| 915 | case llvm::Triple::loongarch32: |
| 916 | case llvm::Triple::loongarch64: |
| 917 | loongarch::getLoongArchTargetFeatures(D, Triple, Args, Features); |
| 918 | break; |
| 919 | } |
| 920 | |
| 921 | for (auto Feature : unifyTargetFeatures(Features)) { |
| 922 | CmdArgs.push_back(Elt: IsAux ? "-aux-target-feature" : "-target-feature" ); |
| 923 | CmdArgs.push_back(Elt: Feature.data()); |
| 924 | } |
| 925 | } |
| 926 | |
| 927 | llvm::StringRef tools::getLTOParallelism(const ArgList &Args, const Driver &D) { |
| 928 | Arg *LtoJobsArg = Args.getLastArg(Ids: options::OPT_flto_jobs_EQ); |
| 929 | if (!LtoJobsArg) |
| 930 | return {}; |
| 931 | if (!llvm::get_threadpool_strategy(Num: LtoJobsArg->getValue())) |
| 932 | D.Diag(DiagID: diag::err_drv_invalid_int_value) |
| 933 | << LtoJobsArg->getAsString(Args) << LtoJobsArg->getValue(); |
| 934 | return LtoJobsArg->getValue(); |
| 935 | } |
| 936 | |
| 937 | // PS4/PS5 uses -ffunction-sections and -fdata-sections by default. |
| 938 | bool tools::isUseSeparateSections(const llvm::Triple &Triple) { |
| 939 | return Triple.isPS(); |
| 940 | } |
| 941 | |
| 942 | bool tools::isTLSDESCEnabled(const ToolChain &TC, |
| 943 | const llvm::opt::ArgList &Args) { |
| 944 | const llvm::Triple &Triple = TC.getEffectiveTriple(); |
| 945 | Arg *A = Args.getLastArg(Ids: options::OPT_mtls_dialect_EQ); |
| 946 | if (!A) |
| 947 | return Triple.hasDefaultTLSDESC(); |
| 948 | StringRef V = A->getValue(); |
| 949 | bool SupportedArgument = false, EnableTLSDESC = false; |
| 950 | bool Unsupported = !Triple.isOSBinFormatELF(); |
| 951 | if (Triple.isLoongArch() || Triple.isRISCV()) { |
| 952 | SupportedArgument = V == "desc" || V == "trad" ; |
| 953 | EnableTLSDESC = V == "desc" ; |
| 954 | } else if (Triple.isX86()) { |
| 955 | SupportedArgument = V == "gnu" || V == "gnu2" ; |
| 956 | EnableTLSDESC = V == "gnu2" ; |
| 957 | } else { |
| 958 | Unsupported = true; |
| 959 | } |
| 960 | if (Unsupported) { |
| 961 | TC.getDriver().Diag(DiagID: diag::err_drv_unsupported_opt_for_target) |
| 962 | << A->getSpelling() << Triple.getTriple(); |
| 963 | } else if (!SupportedArgument) { |
| 964 | TC.getDriver().Diag(DiagID: diag::err_drv_unsupported_option_argument_for_target) |
| 965 | << A->getSpelling() << V << Triple.getTriple(); |
| 966 | } |
| 967 | return EnableTLSDESC; |
| 968 | } |
| 969 | |
| 970 | void tools::addDTLTOOptions(const ToolChain &ToolChain, const ArgList &Args, |
| 971 | llvm::opt::ArgStringList &CmdArgs) { |
| 972 | if (Arg *A = Args.getLastArg(Ids: options::OPT_fthinlto_distributor_EQ)) { |
| 973 | CmdArgs.push_back( |
| 974 | Elt: Args.MakeArgString(Str: "--thinlto-distributor=" + Twine(A->getValue()))); |
| 975 | const Driver &D = ToolChain.getDriver(); |
| 976 | CmdArgs.push_back(Elt: Args.MakeArgString(Str: "--thinlto-remote-compiler=" + |
| 977 | Twine(D.getClangProgramPath()))); |
| 978 | if (auto *PA = D.getPrependArg()) |
| 979 | CmdArgs.push_back(Elt: Args.MakeArgString( |
| 980 | Str: "--thinlto-remote-compiler-prepend-arg=" + Twine(PA))); |
| 981 | |
| 982 | for (const auto &A : |
| 983 | Args.getAllArgValues(Id: options::OPT_Xthinlto_distributor_EQ)) |
| 984 | CmdArgs.push_back(Elt: Args.MakeArgString(Str: "--thinlto-distributor-arg=" + A)); |
| 985 | } |
| 986 | } |
| 987 | |
| 988 | void tools::addLTOOptions(const ToolChain &ToolChain, const ArgList &Args, |
| 989 | ArgStringList &CmdArgs, const InputInfo &Output, |
| 990 | const InputInfoList &Inputs, bool IsThinLTO) { |
| 991 | const llvm::Triple &Triple = ToolChain.getTriple(); |
| 992 | const bool IsOSAIX = Triple.isOSAIX(); |
| 993 | const bool IsAMDGCN = Triple.isAMDGCN(); |
| 994 | StringRef Linker = Args.getLastArgValue(Id: options::OPT_fuse_ld_EQ); |
| 995 | const char *LinkerPath = Args.MakeArgString(Str: ToolChain.GetLinkerPath()); |
| 996 | const Driver &D = ToolChain.getDriver(); |
| 997 | const bool IsFatLTO = Args.hasFlag(Pos: options::OPT_ffat_lto_objects, |
| 998 | Neg: options::OPT_fno_fat_lto_objects, Default: false); |
| 999 | const bool IsUnifiedLTO = Args.hasArg(Ids: options::OPT_funified_lto); |
| 1000 | |
| 1001 | assert(!Inputs.empty() && "Must have at least one input." ); |
| 1002 | |
| 1003 | auto Input = llvm::find_if( |
| 1004 | Range: Inputs, P: [](const InputInfo &II) -> bool { return II.isFilename(); }); |
| 1005 | if (Input == Inputs.end()) { |
| 1006 | // For a very rare case, all of the inputs to the linker are |
| 1007 | // InputArg. If that happens, just use the first InputInfo. |
| 1008 | Input = Inputs.begin(); |
| 1009 | } |
| 1010 | |
| 1011 | if (Linker != "lld" && Linker != "lld-link" && |
| 1012 | llvm::sys::path::filename(path: LinkerPath) != "ld.lld" && |
| 1013 | llvm::sys::path::stem(path: LinkerPath) != "ld.lld" && !Triple.isOSOpenBSD()) { |
| 1014 | // Tell the linker to load the plugin. This has to come before |
| 1015 | // AddLinkerInputs as gold requires -plugin and AIX ld requires -bplugin to |
| 1016 | // come before any -plugin-opt/-bplugin_opt that -Wl might forward. |
| 1017 | const char *PluginPrefix = IsOSAIX ? "-bplugin:" : "" ; |
| 1018 | const char *PluginName = IsOSAIX ? "/libLTO" : "/LLVMgold" ; |
| 1019 | |
| 1020 | if (!IsOSAIX) |
| 1021 | CmdArgs.push_back(Elt: "-plugin" ); |
| 1022 | |
| 1023 | #if defined(_WIN32) |
| 1024 | const char *Suffix = ".dll" ; |
| 1025 | #elif defined(__APPLE__) |
| 1026 | const char *Suffix = ".dylib" ; |
| 1027 | #else |
| 1028 | const char *Suffix = ".so" ; |
| 1029 | #endif |
| 1030 | |
| 1031 | SmallString<1024> Plugin; |
| 1032 | llvm::sys::path::native(path: Twine(D.Dir) + |
| 1033 | "/../" CLANG_INSTALL_LIBDIR_BASENAME + |
| 1034 | PluginName + Suffix, |
| 1035 | result&: Plugin); |
| 1036 | CmdArgs.push_back(Elt: Args.MakeArgString(Str: Twine(PluginPrefix) + Plugin)); |
| 1037 | } else { |
| 1038 | // Tell LLD to find and use .llvm.lto section in regular relocatable object |
| 1039 | // files |
| 1040 | if (IsFatLTO) |
| 1041 | CmdArgs.push_back(Elt: "--fat-lto-objects" ); |
| 1042 | |
| 1043 | if (Args.hasArg(Ids: options::OPT_flto_partitions_EQ)) { |
| 1044 | int Value = 0; |
| 1045 | StringRef A = Args.getLastArgValue(Id: options::OPT_flto_partitions_EQ, Default: "8" ); |
| 1046 | if (A.getAsInteger(Radix: 10, Result&: Value) || (Value < 1)) { |
| 1047 | Arg *Arg = Args.getLastArg(Ids: options::OPT_flto_partitions_EQ); |
| 1048 | D.Diag(DiagID: diag::err_drv_invalid_int_value) |
| 1049 | << Arg->getAsString(Args) << Arg->getValue(); |
| 1050 | } |
| 1051 | CmdArgs.push_back(Elt: Args.MakeArgString(Str: "--lto-partitions=" + A)); |
| 1052 | } |
| 1053 | } |
| 1054 | |
| 1055 | const char *PluginOptPrefix = IsOSAIX ? "-bplugin_opt:" : "-plugin-opt=" ; |
| 1056 | const char * = IsOSAIX ? "-" : "" ; |
| 1057 | const char *ParallelismOpt = IsOSAIX ? "-threads=" : "jobs=" ; |
| 1058 | |
| 1059 | // Note, this solution is far from perfect, better to encode it into IR |
| 1060 | // metadata, but this may not be worth it, since it looks like aranges is on |
| 1061 | // the way out. |
| 1062 | if (Args.hasArg(Ids: options::OPT_gdwarf_aranges)) { |
| 1063 | CmdArgs.push_back(Elt: Args.MakeArgString(Str: Twine(PluginOptPrefix) + |
| 1064 | "-generate-arange-section" )); |
| 1065 | } |
| 1066 | |
| 1067 | // Pass vector library arguments to LTO. |
| 1068 | Arg *ArgVecLib = Args.getLastArg(Ids: options::OPT_fveclib); |
| 1069 | if (ArgVecLib && ArgVecLib->getNumValues() == 1) { |
| 1070 | // Map the vector library names from clang front-end to opt front-end. The |
| 1071 | // values are taken from the TargetLibraryInfo class command line options. |
| 1072 | std::optional<StringRef> OptVal = |
| 1073 | llvm::StringSwitch<std::optional<StringRef>>(ArgVecLib->getValue()) |
| 1074 | .Case(S: "Accelerate" , Value: "Accelerate" ) |
| 1075 | .Case(S: "libmvec" , Value: "LIBMVEC" ) |
| 1076 | .Case(S: "AMDLIBM" , Value: "AMDLIBM" ) |
| 1077 | .Case(S: "MASSV" , Value: "MASSV" ) |
| 1078 | .Case(S: "SVML" , Value: "SVML" ) |
| 1079 | .Case(S: "SLEEF" , Value: "sleefgnuabi" ) |
| 1080 | .Case(S: "Darwin_libsystem_m" , Value: "Darwin_libsystem_m" ) |
| 1081 | .Case(S: "ArmPL" , Value: "ArmPL" ) |
| 1082 | .Case(S: "none" , Value: "none" ) |
| 1083 | .Default(Value: std::nullopt); |
| 1084 | |
| 1085 | if (OptVal) |
| 1086 | CmdArgs.push_back(Elt: Args.MakeArgString( |
| 1087 | Str: Twine(PluginOptPrefix) + "-vector-library=" + OptVal.value())); |
| 1088 | } |
| 1089 | |
| 1090 | // Try to pass driver level flags relevant to LTO code generation down to |
| 1091 | // the plugin. |
| 1092 | |
| 1093 | // Handle flags for selecting CPU variants. |
| 1094 | std::string CPU = getCPUName(D, Args, T: Triple); |
| 1095 | if (!CPU.empty()) |
| 1096 | CmdArgs.push_back( |
| 1097 | Elt: Args.MakeArgString(Str: Twine(PluginOptPrefix) + ExtraDash + "mcpu=" + CPU)); |
| 1098 | |
| 1099 | if (Args.getLastArg(Ids: options::OPT_O_Group)) { |
| 1100 | unsigned OptimizationLevel = |
| 1101 | getOptimizationLevel(Args, IK: InputKind(), Diags&: D.getDiags()); |
| 1102 | CmdArgs.push_back(Elt: Args.MakeArgString(Str: Twine(PluginOptPrefix) + ExtraDash + |
| 1103 | "O" + Twine(OptimizationLevel))); |
| 1104 | if (IsAMDGCN) |
| 1105 | CmdArgs.push_back( |
| 1106 | Elt: Args.MakeArgString(Str: Twine("--lto-CGO" ) + Twine(OptimizationLevel))); |
| 1107 | } |
| 1108 | |
| 1109 | if (Args.hasArg(Ids: options::OPT_gsplit_dwarf)) { |
| 1110 | SmallString<128> F; |
| 1111 | if (const Arg *A = Args.getLastArg(Ids: options::OPT_dumpdir)) { |
| 1112 | F = A->getValue(); |
| 1113 | } else { |
| 1114 | F = Output.getFilename(); |
| 1115 | F += "_" ; |
| 1116 | } |
| 1117 | CmdArgs.push_back( |
| 1118 | Elt: Args.MakeArgString(Str: Twine(PluginOptPrefix) + "dwo_dir=" + F + "dwo" )); |
| 1119 | } |
| 1120 | |
| 1121 | if (IsThinLTO && !IsOSAIX) |
| 1122 | CmdArgs.push_back(Elt: Args.MakeArgString(Str: Twine(PluginOptPrefix) + "thinlto" )); |
| 1123 | else if (IsThinLTO && IsOSAIX) |
| 1124 | CmdArgs.push_back(Elt: Args.MakeArgString(Str: Twine("-bdbg:thinlto" ))); |
| 1125 | |
| 1126 | // Matrix intrinsic lowering happens at link time with ThinLTO. Enable |
| 1127 | // LowerMatrixIntrinsicsPass, which is transitively called by |
| 1128 | // buildThinLTODefaultPipeline under EnableMatrix. |
| 1129 | if ((IsThinLTO || IsFatLTO || IsUnifiedLTO) && |
| 1130 | Args.hasArg(Ids: options::OPT_fenable_matrix)) |
| 1131 | CmdArgs.push_back( |
| 1132 | Elt: Args.MakeArgString(Str: Twine(PluginOptPrefix) + "-enable-matrix" )); |
| 1133 | |
| 1134 | StringRef Parallelism = getLTOParallelism(Args, D); |
| 1135 | if (!Parallelism.empty()) |
| 1136 | CmdArgs.push_back(Elt: Args.MakeArgString(Str: Twine(PluginOptPrefix) + |
| 1137 | ParallelismOpt + Parallelism)); |
| 1138 | |
| 1139 | // Pass down GlobalISel options. |
| 1140 | if (Arg *A = Args.getLastArg(Ids: options::OPT_fglobal_isel, |
| 1141 | Ids: options::OPT_fno_global_isel)) { |
| 1142 | // Parsing -fno-global-isel explicitly gives architectures that enable GISel |
| 1143 | // by default a chance to disable it. |
| 1144 | CmdArgs.push_back(Elt: Args.MakeArgString( |
| 1145 | Str: Twine(PluginOptPrefix) + "-global-isel=" + |
| 1146 | (A->getOption().matches(ID: options::OPT_fglobal_isel) ? "1" : "0" ))); |
| 1147 | } |
| 1148 | |
| 1149 | // If an explicit debugger tuning argument appeared, pass it along. |
| 1150 | if (Arg *A = |
| 1151 | Args.getLastArg(Ids: options::OPT_gTune_Group, Ids: options::OPT_ggdbN_Group)) { |
| 1152 | if (A->getOption().matches(ID: options::OPT_glldb)) |
| 1153 | CmdArgs.push_back( |
| 1154 | Elt: Args.MakeArgString(Str: Twine(PluginOptPrefix) + "-debugger-tune=lldb" )); |
| 1155 | else if (A->getOption().matches(ID: options::OPT_gsce)) |
| 1156 | CmdArgs.push_back( |
| 1157 | Elt: Args.MakeArgString(Str: Twine(PluginOptPrefix) + "-debugger-tune=sce" )); |
| 1158 | else if (A->getOption().matches(ID: options::OPT_gdbx)) |
| 1159 | CmdArgs.push_back( |
| 1160 | Elt: Args.MakeArgString(Str: Twine(PluginOptPrefix) + "-debugger-tune=dbx" )); |
| 1161 | else |
| 1162 | CmdArgs.push_back( |
| 1163 | Elt: Args.MakeArgString(Str: Twine(PluginOptPrefix) + "-debugger-tune=gdb" )); |
| 1164 | } |
| 1165 | |
| 1166 | if (IsOSAIX) { |
| 1167 | if (!ToolChain.useIntegratedAs()) |
| 1168 | CmdArgs.push_back( |
| 1169 | Elt: Args.MakeArgString(Str: Twine(PluginOptPrefix) + "-no-integrated-as=1" )); |
| 1170 | |
| 1171 | // On AIX, clang assumes strict-dwarf is true if any debug option is |
| 1172 | // specified, unless it is told explicitly not to assume so. |
| 1173 | Arg *A = Args.getLastArg(Ids: options::OPT_g_Group); |
| 1174 | bool EnableDebugInfo = A && !A->getOption().matches(ID: options::OPT_g0) && |
| 1175 | !A->getOption().matches(ID: options::OPT_ggdb0); |
| 1176 | if (EnableDebugInfo && Args.hasFlag(Pos: options::OPT_gstrict_dwarf, |
| 1177 | Neg: options::OPT_gno_strict_dwarf, Default: true)) |
| 1178 | CmdArgs.push_back( |
| 1179 | Elt: Args.MakeArgString(Str: Twine(PluginOptPrefix) + "-strict-dwarf=true" )); |
| 1180 | |
| 1181 | for (const Arg *A : Args.filtered_reverse(Ids: options::OPT_mabi_EQ)) { |
| 1182 | StringRef V = A->getValue(); |
| 1183 | if (V == "vec-default" ) |
| 1184 | break; |
| 1185 | if (V == "vec-extabi" ) { |
| 1186 | CmdArgs.push_back( |
| 1187 | Elt: Args.MakeArgString(Str: Twine(PluginOptPrefix) + "-vec-extabi" )); |
| 1188 | break; |
| 1189 | } |
| 1190 | } |
| 1191 | } |
| 1192 | |
| 1193 | bool UseSeparateSections = |
| 1194 | isUseSeparateSections(Triple: ToolChain.getEffectiveTriple()); |
| 1195 | |
| 1196 | if (Args.hasFlag(Pos: options::OPT_ffunction_sections, |
| 1197 | Neg: options::OPT_fno_function_sections, Default: UseSeparateSections)) |
| 1198 | CmdArgs.push_back( |
| 1199 | Elt: Args.MakeArgString(Str: Twine(PluginOptPrefix) + "-function-sections=1" )); |
| 1200 | else if (Args.hasArg(Ids: options::OPT_fno_function_sections)) |
| 1201 | CmdArgs.push_back( |
| 1202 | Elt: Args.MakeArgString(Str: Twine(PluginOptPrefix) + "-function-sections=0" )); |
| 1203 | |
| 1204 | bool DataSectionsTurnedOff = false; |
| 1205 | if (Args.hasFlag(Pos: options::OPT_fdata_sections, Neg: options::OPT_fno_data_sections, |
| 1206 | Default: UseSeparateSections)) { |
| 1207 | CmdArgs.push_back( |
| 1208 | Elt: Args.MakeArgString(Str: Twine(PluginOptPrefix) + "-data-sections=1" )); |
| 1209 | } else if (Args.hasArg(Ids: options::OPT_fno_data_sections)) { |
| 1210 | DataSectionsTurnedOff = true; |
| 1211 | CmdArgs.push_back( |
| 1212 | Elt: Args.MakeArgString(Str: Twine(PluginOptPrefix) + "-data-sections=0" )); |
| 1213 | } |
| 1214 | |
| 1215 | if (Args.hasArg(Ids: options::OPT_mxcoff_roptr) || |
| 1216 | Args.hasArg(Ids: options::OPT_mno_xcoff_roptr)) { |
| 1217 | bool HasRoptr = Args.hasFlag(Pos: options::OPT_mxcoff_roptr, |
| 1218 | Neg: options::OPT_mno_xcoff_roptr, Default: false); |
| 1219 | StringRef OptStr = HasRoptr ? "-mxcoff-roptr" : "-mno-xcoff-roptr" ; |
| 1220 | if (!IsOSAIX) |
| 1221 | D.Diag(DiagID: diag::err_drv_unsupported_opt_for_target) |
| 1222 | << OptStr << Triple.str(); |
| 1223 | |
| 1224 | if (HasRoptr) { |
| 1225 | // The data sections option is on by default on AIX. We only need to error |
| 1226 | // out when -fno-data-sections is specified explicitly to turn off data |
| 1227 | // sections. |
| 1228 | if (DataSectionsTurnedOff) |
| 1229 | D.Diag(DiagID: diag::err_roptr_requires_data_sections); |
| 1230 | |
| 1231 | CmdArgs.push_back( |
| 1232 | Elt: Args.MakeArgString(Str: Twine(PluginOptPrefix) + "-mxcoff-roptr" )); |
| 1233 | } |
| 1234 | } |
| 1235 | |
| 1236 | // Pass an option to enable split machine functions. |
| 1237 | if (auto *A = Args.getLastArg(Ids: options::OPT_fsplit_machine_functions, |
| 1238 | Ids: options::OPT_fno_split_machine_functions)) { |
| 1239 | if (A->getOption().matches(ID: options::OPT_fsplit_machine_functions)) |
| 1240 | CmdArgs.push_back(Elt: Args.MakeArgString(Str: Twine(PluginOptPrefix) + |
| 1241 | "-split-machine-functions" )); |
| 1242 | } |
| 1243 | |
| 1244 | if (auto *A = |
| 1245 | Args.getLastArg(Ids: options::OPT_fpartition_static_data_sections, |
| 1246 | Ids: options::OPT_fno_partition_static_data_sections)) { |
| 1247 | if (A->getOption().matches(ID: options::OPT_fpartition_static_data_sections)) { |
| 1248 | CmdArgs.push_back(Elt: Args.MakeArgString(Str: Twine(PluginOptPrefix) + |
| 1249 | "-partition-static-data-sections" )); |
| 1250 | } |
| 1251 | } |
| 1252 | |
| 1253 | if (Arg *A = getLastProfileSampleUseArg(Args)) { |
| 1254 | StringRef FName = A->getValue(); |
| 1255 | if (!llvm::sys::fs::exists(Path: FName)) |
| 1256 | D.Diag(DiagID: diag::err_drv_no_such_file) << FName; |
| 1257 | else |
| 1258 | CmdArgs.push_back(Elt: Args.MakeArgString(Str: Twine(PluginOptPrefix) + |
| 1259 | "sample-profile=" + FName)); |
| 1260 | } |
| 1261 | |
| 1262 | if (auto *CSPGOGenerateArg = getLastCSProfileGenerateArg(Args)) { |
| 1263 | CmdArgs.push_back(Elt: Args.MakeArgString(Str: Twine(PluginOptPrefix) + ExtraDash + |
| 1264 | "cs-profile-generate" )); |
| 1265 | if (CSPGOGenerateArg->getOption().matches( |
| 1266 | ID: options::OPT_fcs_profile_generate_EQ)) { |
| 1267 | SmallString<128> Path(CSPGOGenerateArg->getValue()); |
| 1268 | llvm::sys::path::append(path&: Path, a: "default_%m.profraw" ); |
| 1269 | CmdArgs.push_back(Elt: Args.MakeArgString(Str: Twine(PluginOptPrefix) + ExtraDash + |
| 1270 | "cs-profile-path=" + Path)); |
| 1271 | } else |
| 1272 | CmdArgs.push_back( |
| 1273 | Elt: Args.MakeArgString(Str: Twine(PluginOptPrefix) + ExtraDash + |
| 1274 | "cs-profile-path=default_%m.profraw" )); |
| 1275 | } else if (auto *ProfileUseArg = getLastProfileUseArg(Args)) { |
| 1276 | SmallString<128> Path( |
| 1277 | ProfileUseArg->getNumValues() == 0 ? "" : ProfileUseArg->getValue()); |
| 1278 | if (Path.empty() || llvm::sys::fs::is_directory(Path)) |
| 1279 | llvm::sys::path::append(path&: Path, a: "default.profdata" ); |
| 1280 | CmdArgs.push_back(Elt: Args.MakeArgString(Str: Twine(PluginOptPrefix) + ExtraDash + |
| 1281 | "cs-profile-path=" + Path)); |
| 1282 | } |
| 1283 | |
| 1284 | // This controls whether or not we perform JustMyCode instrumentation. |
| 1285 | if (Args.hasFlag(Pos: options::OPT_fjmc, Neg: options::OPT_fno_jmc, Default: false)) { |
| 1286 | if (ToolChain.getEffectiveTriple().isOSBinFormatELF()) |
| 1287 | CmdArgs.push_back(Elt: Args.MakeArgString(Str: Twine(PluginOptPrefix) + |
| 1288 | "-enable-jmc-instrument" )); |
| 1289 | else |
| 1290 | D.Diag(DiagID: clang::diag::warn_drv_fjmc_for_elf_only); |
| 1291 | } |
| 1292 | |
| 1293 | if (Args.hasFlag(Pos: options::OPT_femulated_tls, Neg: options::OPT_fno_emulated_tls, |
| 1294 | Default: Triple.hasDefaultEmulatedTLS())) { |
| 1295 | CmdArgs.push_back( |
| 1296 | Elt: Args.MakeArgString(Str: Twine(PluginOptPrefix) + "-emulated-tls" )); |
| 1297 | } |
| 1298 | if (isTLSDESCEnabled(TC: ToolChain, Args)) |
| 1299 | CmdArgs.push_back( |
| 1300 | Elt: Args.MakeArgString(Str: Twine(PluginOptPrefix) + "-enable-tlsdesc" )); |
| 1301 | |
| 1302 | if (Args.hasFlag(Pos: options::OPT_fstack_size_section, |
| 1303 | Neg: options::OPT_fno_stack_size_section, Default: false)) |
| 1304 | CmdArgs.push_back( |
| 1305 | Elt: Args.MakeArgString(Str: Twine(PluginOptPrefix) + "-stack-size-section" )); |
| 1306 | |
| 1307 | if (Args.hasFlag(Pos: options::OPT_fexperimental_call_graph_section, |
| 1308 | Neg: options::OPT_fno_experimental_call_graph_section, Default: false)) |
| 1309 | CmdArgs.push_back( |
| 1310 | Elt: Args.MakeArgString(Str: Twine(PluginOptPrefix) + "-call-graph-section" )); |
| 1311 | |
| 1312 | // Setup statistics file output. |
| 1313 | SmallString<128> StatsFile = getStatsFileName(Args, Output, Input: *Input, D); |
| 1314 | if (!StatsFile.empty()) |
| 1315 | CmdArgs.push_back( |
| 1316 | Elt: Args.MakeArgString(Str: Twine(PluginOptPrefix) + "stats-file=" + StatsFile)); |
| 1317 | |
| 1318 | // Setup crash diagnostics dir. |
| 1319 | if (Arg *A = Args.getLastArg(Ids: options::OPT_fcrash_diagnostics_dir)) |
| 1320 | CmdArgs.push_back(Elt: Args.MakeArgString( |
| 1321 | Str: Twine(PluginOptPrefix) + "-crash-diagnostics-dir=" + A->getValue())); |
| 1322 | |
| 1323 | addX86AlignBranchArgs(D, Args, CmdArgs, /*IsLTO=*/true, PluginOptPrefix); |
| 1324 | |
| 1325 | // Handle remark diagnostics on screen options: '-Rpass-*'. |
| 1326 | renderRpassOptions(Args, CmdArgs, PluginOptPrefix); |
| 1327 | |
| 1328 | // Handle serialized remarks options: '-fsave-optimization-record' |
| 1329 | // and '-foptimization-record-*'. |
| 1330 | if (willEmitRemarks(Args)) |
| 1331 | renderRemarksOptions(Args, CmdArgs, Triple: ToolChain.getEffectiveTriple(), Input: *Input, |
| 1332 | Output, PluginOptPrefix); |
| 1333 | |
| 1334 | // Handle remarks hotness/threshold related options. |
| 1335 | renderRemarksHotnessOptions(Args, CmdArgs, PluginOptPrefix); |
| 1336 | |
| 1337 | addMachineOutlinerArgs(D, Args, CmdArgs, Triple: ToolChain.getEffectiveTriple(), |
| 1338 | /*IsLTO=*/true, PluginOptPrefix); |
| 1339 | |
| 1340 | bool IsELF = Triple.isOSBinFormatELF(); |
| 1341 | bool Crel = false; |
| 1342 | bool ImplicitMapSyms = false; |
| 1343 | for (const Arg *A : Args.filtered(Ids: options::OPT_Wa_COMMA)) { |
| 1344 | for (StringRef V : A->getValues()) { |
| 1345 | auto Equal = V.split(Separator: '='); |
| 1346 | auto checkArg = [&](bool ValidTarget, |
| 1347 | std::initializer_list<const char *> Set) { |
| 1348 | if (!ValidTarget) { |
| 1349 | D.Diag(DiagID: diag::err_drv_unsupported_opt_for_target) |
| 1350 | << (Twine("-Wa," ) + Equal.first + "=" ).str() |
| 1351 | << Triple.getTriple(); |
| 1352 | } else if (!llvm::is_contained(Set, Element: Equal.second)) { |
| 1353 | D.Diag(DiagID: diag::err_drv_unsupported_option_argument) |
| 1354 | << (Twine("-Wa," ) + Equal.first + "=" ).str() << Equal.second; |
| 1355 | } |
| 1356 | }; |
| 1357 | if (Equal.first == "-mmapsyms" ) { |
| 1358 | ImplicitMapSyms = Equal.second == "implicit" ; |
| 1359 | checkArg(IsELF && Triple.isAArch64(), {"default" , "implicit" }); |
| 1360 | } else if (V == "--crel" ) |
| 1361 | Crel = true; |
| 1362 | else if (V == "--no-crel" ) |
| 1363 | Crel = false; |
| 1364 | else |
| 1365 | continue; |
| 1366 | A->claim(); |
| 1367 | } |
| 1368 | } |
| 1369 | if (Crel) { |
| 1370 | if (IsELF && !Triple.isMIPS()) { |
| 1371 | CmdArgs.push_back(Elt: Args.MakeArgString(Str: Twine(PluginOptPrefix) + "-crel" )); |
| 1372 | } else { |
| 1373 | D.Diag(DiagID: diag::err_drv_unsupported_opt_for_target) |
| 1374 | << "-Wa,--crel" << D.getTargetTriple(); |
| 1375 | } |
| 1376 | } |
| 1377 | if (ImplicitMapSyms) |
| 1378 | CmdArgs.push_back( |
| 1379 | Elt: Args.MakeArgString(Str: Twine(PluginOptPrefix) + "-implicit-mapsyms" )); |
| 1380 | |
| 1381 | if (Args.hasArg(Ids: options::OPT_ftime_report)) |
| 1382 | CmdArgs.push_back( |
| 1383 | Elt: Args.MakeArgString(Str: Twine(PluginOptPrefix) + "-time-passes" )); |
| 1384 | |
| 1385 | addDTLTOOptions(ToolChain, Args, CmdArgs); |
| 1386 | } |
| 1387 | |
| 1388 | void tools::addOpenMPRuntimeLibraryPath(const ToolChain &TC, |
| 1389 | const ArgList &Args, |
| 1390 | ArgStringList &CmdArgs) { |
| 1391 | // Default to clang lib / lib64 folder, i.e. the same location as device |
| 1392 | // runtime. |
| 1393 | SmallString<256> DefaultLibPath = |
| 1394 | llvm::sys::path::parent_path(path: TC.getDriver().Dir); |
| 1395 | llvm::sys::path::append(path&: DefaultLibPath, CLANG_INSTALL_LIBDIR_BASENAME); |
| 1396 | CmdArgs.push_back(Elt: Args.MakeArgString(Str: "-L" + DefaultLibPath)); |
| 1397 | } |
| 1398 | |
| 1399 | void tools::addArchSpecificRPath(const ToolChain &TC, const ArgList &Args, |
| 1400 | ArgStringList &CmdArgs) { |
| 1401 | if (!Args.hasFlag(Pos: options::OPT_frtlib_add_rpath, |
| 1402 | Neg: options::OPT_fno_rtlib_add_rpath, Default: false)) |
| 1403 | return; |
| 1404 | |
| 1405 | if (TC.getTriple().isOSAIX()) // TODO: AIX doesn't support -rpath option. |
| 1406 | return; |
| 1407 | |
| 1408 | SmallVector<std::string> CandidateRPaths(TC.getArchSpecificLibPaths()); |
| 1409 | if (const auto CandidateRPath = TC.getStdlibPath()) |
| 1410 | CandidateRPaths.emplace_back(Args: *CandidateRPath); |
| 1411 | |
| 1412 | for (const auto &CandidateRPath : CandidateRPaths) { |
| 1413 | if (TC.getVFS().exists(Path: CandidateRPath)) { |
| 1414 | CmdArgs.push_back(Elt: "-rpath" ); |
| 1415 | CmdArgs.push_back(Elt: Args.MakeArgString(Str: CandidateRPath)); |
| 1416 | } |
| 1417 | } |
| 1418 | } |
| 1419 | |
| 1420 | bool tools::addOpenMPRuntime(const Compilation &C, ArgStringList &CmdArgs, |
| 1421 | const ToolChain &TC, const ArgList &Args, |
| 1422 | bool ForceStaticHostRuntime, bool IsOffloadingHost, |
| 1423 | bool GompNeedsRT) { |
| 1424 | if (!Args.hasFlag(Pos: options::OPT_fopenmp, PosAlias: options::OPT_fopenmp_EQ, |
| 1425 | Neg: options::OPT_fno_openmp, Default: false)) { |
| 1426 | // We need libomptarget (liboffload) if it's the choosen offloading runtime. |
| 1427 | if (Args.hasFlag(Pos: options::OPT_foffload_via_llvm, |
| 1428 | Neg: options::OPT_fno_offload_via_llvm, Default: false)) |
| 1429 | CmdArgs.push_back(Elt: "-lomptarget" ); |
| 1430 | return false; |
| 1431 | } |
| 1432 | |
| 1433 | Driver::OpenMPRuntimeKind RTKind = TC.getDriver().getOpenMPRuntime(Args); |
| 1434 | |
| 1435 | if (RTKind == Driver::OMPRT_Unknown) |
| 1436 | // Already diagnosed. |
| 1437 | return false; |
| 1438 | |
| 1439 | if (ForceStaticHostRuntime) |
| 1440 | CmdArgs.push_back(Elt: "-Bstatic" ); |
| 1441 | |
| 1442 | switch (RTKind) { |
| 1443 | case Driver::OMPRT_OMP: |
| 1444 | CmdArgs.push_back(Elt: "-lomp" ); |
| 1445 | break; |
| 1446 | case Driver::OMPRT_GOMP: |
| 1447 | CmdArgs.push_back(Elt: "-lgomp" ); |
| 1448 | break; |
| 1449 | case Driver::OMPRT_IOMP5: |
| 1450 | CmdArgs.push_back(Elt: "-liomp5" ); |
| 1451 | break; |
| 1452 | case Driver::OMPRT_Unknown: |
| 1453 | break; |
| 1454 | } |
| 1455 | |
| 1456 | if (ForceStaticHostRuntime) |
| 1457 | CmdArgs.push_back(Elt: "-Bdynamic" ); |
| 1458 | |
| 1459 | if (RTKind == Driver::OMPRT_GOMP && GompNeedsRT) |
| 1460 | CmdArgs.push_back(Elt: "-lrt" ); |
| 1461 | |
| 1462 | if (IsOffloadingHost) |
| 1463 | CmdArgs.push_back(Elt: "-lomptarget" ); |
| 1464 | |
| 1465 | addArchSpecificRPath(TC, Args, CmdArgs); |
| 1466 | |
| 1467 | addOpenMPRuntimeLibraryPath(TC, Args, CmdArgs); |
| 1468 | |
| 1469 | return true; |
| 1470 | } |
| 1471 | |
| 1472 | void tools::addOpenMPHostOffloadingArgs(const Compilation &C, |
| 1473 | const JobAction &JA, |
| 1474 | const llvm::opt::ArgList &Args, |
| 1475 | llvm::opt::ArgStringList &CmdArgs) { |
| 1476 | if (!JA.isHostOffloading(OKind: Action::OFK_OpenMP)) |
| 1477 | return; |
| 1478 | |
| 1479 | // For all the host OpenMP offloading compile jobs we need to pass the targets |
| 1480 | // information using -fopenmp-targets= option. |
| 1481 | constexpr llvm::StringLiteral Targets("--offload-targets=" ); |
| 1482 | |
| 1483 | SmallVector<std::string> Triples; |
| 1484 | auto TCRange = C.getOffloadToolChains<Action::OFK_OpenMP>(); |
| 1485 | std::transform(first: TCRange.first, last: TCRange.second, result: std::back_inserter(x&: Triples), |
| 1486 | unary_op: [](auto TC) { return TC.second->getTripleString(); }); |
| 1487 | CmdArgs.push_back( |
| 1488 | Elt: Args.MakeArgString(Str: Twine(Targets) + llvm::join(R&: Triples, Separator: "," ))); |
| 1489 | } |
| 1490 | |
| 1491 | static void addSanitizerRuntime(const ToolChain &TC, const ArgList &Args, |
| 1492 | ArgStringList &CmdArgs, StringRef Sanitizer, |
| 1493 | bool IsShared, bool IsWhole) { |
| 1494 | // Wrap any static runtimes that must be forced into executable in |
| 1495 | // whole-archive. |
| 1496 | if (IsWhole) CmdArgs.push_back(Elt: "--whole-archive" ); |
| 1497 | CmdArgs.push_back(Elt: TC.getCompilerRTArgString( |
| 1498 | Args, Component: Sanitizer, Type: IsShared ? ToolChain::FT_Shared : ToolChain::FT_Static)); |
| 1499 | if (IsWhole) CmdArgs.push_back(Elt: "--no-whole-archive" ); |
| 1500 | |
| 1501 | if (IsShared) { |
| 1502 | addArchSpecificRPath(TC, Args, CmdArgs); |
| 1503 | } |
| 1504 | } |
| 1505 | |
| 1506 | // Tries to use a file with the list of dynamic symbols that need to be exported |
| 1507 | // from the runtime library. Returns true if the file was found. |
| 1508 | static bool addSanitizerDynamicList(const ToolChain &TC, const ArgList &Args, |
| 1509 | ArgStringList &CmdArgs, |
| 1510 | StringRef Sanitizer) { |
| 1511 | bool LinkerIsGnuLd = solaris::isLinkerGnuLd(TC, Args); |
| 1512 | |
| 1513 | // Solaris ld defaults to --export-dynamic behaviour but doesn't support |
| 1514 | // the option, so don't try to pass it. |
| 1515 | if (TC.getTriple().isOSSolaris() && !LinkerIsGnuLd) |
| 1516 | return true; |
| 1517 | SmallString<128> SanRT(TC.getCompilerRT(Args, Component: Sanitizer)); |
| 1518 | if (llvm::sys::fs::exists(Path: SanRT + ".syms" )) { |
| 1519 | CmdArgs.push_back(Elt: Args.MakeArgString(Str: "--dynamic-list=" + SanRT + ".syms" )); |
| 1520 | return true; |
| 1521 | } |
| 1522 | return false; |
| 1523 | } |
| 1524 | |
| 1525 | void tools::addAsNeededOption(const ToolChain &TC, |
| 1526 | const llvm::opt::ArgList &Args, |
| 1527 | llvm::opt::ArgStringList &CmdArgs, |
| 1528 | bool as_needed) { |
| 1529 | assert(!TC.getTriple().isOSAIX() && |
| 1530 | "AIX linker does not support any form of --as-needed option yet." ); |
| 1531 | bool LinkerIsGnuLd = solaris::isLinkerGnuLd(TC, Args); |
| 1532 | |
| 1533 | // While the Solaris 11.2 ld added --as-needed/--no-as-needed as aliases |
| 1534 | // for the native forms -z ignore/-z record, they are missing in Illumos, |
| 1535 | // so always use the native form. |
| 1536 | // GNU ld doesn't support -z ignore/-z record, so don't use them even on |
| 1537 | // Solaris. |
| 1538 | if (TC.getTriple().isOSSolaris() && !LinkerIsGnuLd) { |
| 1539 | CmdArgs.push_back(Elt: "-z" ); |
| 1540 | CmdArgs.push_back(Elt: as_needed ? "ignore" : "record" ); |
| 1541 | } else { |
| 1542 | CmdArgs.push_back(Elt: as_needed ? "--as-needed" : "--no-as-needed" ); |
| 1543 | } |
| 1544 | } |
| 1545 | |
| 1546 | void tools::linkSanitizerRuntimeDeps(const ToolChain &TC, |
| 1547 | const llvm::opt::ArgList &Args, |
| 1548 | ArgStringList &CmdArgs) { |
| 1549 | // Force linking against the system libraries sanitizers depends on |
| 1550 | // (see PR15823 why this is necessary). |
| 1551 | addAsNeededOption(TC, Args, CmdArgs, as_needed: false); |
| 1552 | // There's no libpthread or librt on RTEMS & Android. |
| 1553 | if (TC.getTriple().getOS() != llvm::Triple::RTEMS && |
| 1554 | !TC.getTriple().isAndroid() && !TC.getTriple().isOHOSFamily()) { |
| 1555 | CmdArgs.push_back(Elt: "-lpthread" ); |
| 1556 | if (!TC.getTriple().isOSOpenBSD() && !TC.getTriple().isOSHaiku()) |
| 1557 | CmdArgs.push_back(Elt: "-lrt" ); |
| 1558 | } |
| 1559 | CmdArgs.push_back(Elt: "-lm" ); |
| 1560 | // There's no libdl on all OSes. |
| 1561 | if (!TC.getTriple().isOSFreeBSD() && !TC.getTriple().isOSNetBSD() && |
| 1562 | !TC.getTriple().isOSOpenBSD() && !TC.getTriple().isOSDragonFly() && |
| 1563 | !TC.getTriple().isOSHaiku() && |
| 1564 | TC.getTriple().getOS() != llvm::Triple::RTEMS) |
| 1565 | CmdArgs.push_back(Elt: "-ldl" ); |
| 1566 | // Required for backtrace on some OSes |
| 1567 | if (TC.getTriple().isOSFreeBSD() || TC.getTriple().isOSNetBSD() || |
| 1568 | TC.getTriple().isOSOpenBSD() || TC.getTriple().isOSDragonFly()) |
| 1569 | CmdArgs.push_back(Elt: "-lexecinfo" ); |
| 1570 | if (TC.getTriple().isOSHaiku()) |
| 1571 | CmdArgs.push_back(Elt: "-lbsd" ); |
| 1572 | // There is no libresolv on Android, FreeBSD, OpenBSD, etc. On musl |
| 1573 | // libresolv.a, even if exists, is an empty archive to satisfy POSIX -lresolv |
| 1574 | // requirement. |
| 1575 | if (TC.getTriple().isOSLinux() && !TC.getTriple().isAndroid() && |
| 1576 | !TC.getTriple().isMusl()) |
| 1577 | CmdArgs.push_back(Elt: "-lresolv" ); |
| 1578 | } |
| 1579 | |
| 1580 | static void |
| 1581 | collectSanitizerRuntimes(const ToolChain &TC, const ArgList &Args, |
| 1582 | SmallVectorImpl<StringRef> &SharedRuntimes, |
| 1583 | SmallVectorImpl<StringRef> &StaticRuntimes, |
| 1584 | SmallVectorImpl<StringRef> &NonWholeStaticRuntimes, |
| 1585 | SmallVectorImpl<StringRef> &HelperStaticRuntimes, |
| 1586 | SmallVectorImpl<StringRef> &RequiredSymbols) { |
| 1587 | assert(!TC.getTriple().isOSDarwin() && "it's not used by Darwin" ); |
| 1588 | const SanitizerArgs &SanArgs = TC.getSanitizerArgs(JobArgs: Args); |
| 1589 | // Collect shared runtimes. |
| 1590 | if (SanArgs.needsSharedRt()) { |
| 1591 | if (SanArgs.needsAsanRt()) { |
| 1592 | SharedRuntimes.push_back(Elt: "asan" ); |
| 1593 | if (!Args.hasArg(Ids: options::OPT_shared) && !TC.getTriple().isAndroid()) |
| 1594 | HelperStaticRuntimes.push_back(Elt: "asan-preinit" ); |
| 1595 | } |
| 1596 | if (SanArgs.needsMemProfRt()) { |
| 1597 | SharedRuntimes.push_back(Elt: "memprof" ); |
| 1598 | if (!Args.hasArg(Ids: options::OPT_shared) && !TC.getTriple().isAndroid()) |
| 1599 | HelperStaticRuntimes.push_back(Elt: "memprof-preinit" ); |
| 1600 | } |
| 1601 | if (SanArgs.needsNsanRt()) |
| 1602 | SharedRuntimes.push_back(Elt: "nsan" ); |
| 1603 | if (SanArgs.needsUbsanRt()) { |
| 1604 | if (SanArgs.requiresMinimalRuntime()) |
| 1605 | SharedRuntimes.push_back(Elt: "ubsan_minimal" ); |
| 1606 | else |
| 1607 | SharedRuntimes.push_back(Elt: "ubsan_standalone" ); |
| 1608 | } |
| 1609 | if (SanArgs.needsScudoRt()) { |
| 1610 | SharedRuntimes.push_back(Elt: "scudo_standalone" ); |
| 1611 | } |
| 1612 | if (SanArgs.needsTsanRt()) |
| 1613 | SharedRuntimes.push_back(Elt: "tsan" ); |
| 1614 | if (SanArgs.needsTysanRt()) |
| 1615 | SharedRuntimes.push_back(Elt: "tysan" ); |
| 1616 | if (SanArgs.needsHwasanRt()) { |
| 1617 | if (SanArgs.needsHwasanAliasesRt()) |
| 1618 | SharedRuntimes.push_back(Elt: "hwasan_aliases" ); |
| 1619 | else |
| 1620 | SharedRuntimes.push_back(Elt: "hwasan" ); |
| 1621 | if (!Args.hasArg(Ids: options::OPT_shared)) |
| 1622 | HelperStaticRuntimes.push_back(Elt: "hwasan-preinit" ); |
| 1623 | } |
| 1624 | if (SanArgs.needsRtsanRt() && SanArgs.linkRuntimes()) |
| 1625 | SharedRuntimes.push_back(Elt: "rtsan" ); |
| 1626 | } |
| 1627 | |
| 1628 | // The stats_client library is also statically linked into DSOs. |
| 1629 | if (SanArgs.needsStatsRt()) |
| 1630 | StaticRuntimes.push_back(Elt: "stats_client" ); |
| 1631 | |
| 1632 | // Always link the static runtime regardless of DSO or executable. |
| 1633 | if (SanArgs.needsAsanRt()) |
| 1634 | HelperStaticRuntimes.push_back(Elt: "asan_static" ); |
| 1635 | |
| 1636 | // Collect static runtimes. |
| 1637 | if (Args.hasArg(Ids: options::OPT_shared)) { |
| 1638 | // Don't link static runtimes into DSOs. |
| 1639 | return; |
| 1640 | } |
| 1641 | |
| 1642 | // Each static runtime that has a DSO counterpart above is excluded below, |
| 1643 | // but runtimes that exist only as static are not affected by needsSharedRt. |
| 1644 | |
| 1645 | if (!SanArgs.needsSharedRt() && SanArgs.needsAsanRt()) { |
| 1646 | StaticRuntimes.push_back(Elt: "asan" ); |
| 1647 | if (SanArgs.linkCXXRuntimes()) |
| 1648 | StaticRuntimes.push_back(Elt: "asan_cxx" ); |
| 1649 | } |
| 1650 | |
| 1651 | if (!SanArgs.needsSharedRt() && SanArgs.needsRtsanRt() && |
| 1652 | SanArgs.linkRuntimes()) |
| 1653 | StaticRuntimes.push_back(Elt: "rtsan" ); |
| 1654 | |
| 1655 | if (!SanArgs.needsSharedRt() && SanArgs.needsMemProfRt()) { |
| 1656 | StaticRuntimes.push_back(Elt: "memprof" ); |
| 1657 | if (SanArgs.linkCXXRuntimes()) |
| 1658 | StaticRuntimes.push_back(Elt: "memprof_cxx" ); |
| 1659 | } |
| 1660 | |
| 1661 | if (!SanArgs.needsSharedRt() && SanArgs.needsHwasanRt()) { |
| 1662 | if (SanArgs.needsHwasanAliasesRt()) { |
| 1663 | StaticRuntimes.push_back(Elt: "hwasan_aliases" ); |
| 1664 | if (SanArgs.linkCXXRuntimes()) |
| 1665 | StaticRuntimes.push_back(Elt: "hwasan_aliases_cxx" ); |
| 1666 | } else { |
| 1667 | StaticRuntimes.push_back(Elt: "hwasan" ); |
| 1668 | if (SanArgs.linkCXXRuntimes()) |
| 1669 | StaticRuntimes.push_back(Elt: "hwasan_cxx" ); |
| 1670 | } |
| 1671 | } |
| 1672 | if (SanArgs.needsDfsanRt()) |
| 1673 | StaticRuntimes.push_back(Elt: "dfsan" ); |
| 1674 | if (SanArgs.needsLsanRt()) |
| 1675 | StaticRuntimes.push_back(Elt: "lsan" ); |
| 1676 | if (SanArgs.needsMsanRt()) { |
| 1677 | StaticRuntimes.push_back(Elt: "msan" ); |
| 1678 | if (SanArgs.linkCXXRuntimes()) |
| 1679 | StaticRuntimes.push_back(Elt: "msan_cxx" ); |
| 1680 | } |
| 1681 | if (!SanArgs.needsSharedRt() && SanArgs.needsNsanRt()) |
| 1682 | StaticRuntimes.push_back(Elt: "nsan" ); |
| 1683 | if (!SanArgs.needsSharedRt() && SanArgs.needsTsanRt()) { |
| 1684 | StaticRuntimes.push_back(Elt: "tsan" ); |
| 1685 | if (SanArgs.linkCXXRuntimes()) |
| 1686 | StaticRuntimes.push_back(Elt: "tsan_cxx" ); |
| 1687 | } |
| 1688 | if (!SanArgs.needsSharedRt() && SanArgs.needsTysanRt()) |
| 1689 | StaticRuntimes.push_back(Elt: "tysan" ); |
| 1690 | if (!SanArgs.needsSharedRt() && SanArgs.needsUbsanRt()) { |
| 1691 | if (SanArgs.requiresMinimalRuntime()) { |
| 1692 | StaticRuntimes.push_back(Elt: "ubsan_minimal" ); |
| 1693 | } else { |
| 1694 | StaticRuntimes.push_back(Elt: "ubsan_standalone" ); |
| 1695 | } |
| 1696 | } |
| 1697 | if (SanArgs.needsSafeStackRt()) { |
| 1698 | NonWholeStaticRuntimes.push_back(Elt: "safestack" ); |
| 1699 | RequiredSymbols.push_back(Elt: "__safestack_init" ); |
| 1700 | } |
| 1701 | if (!(SanArgs.needsSharedRt() && SanArgs.needsUbsanRt())) { |
| 1702 | if (SanArgs.needsCfiCrossDsoRt()) |
| 1703 | StaticRuntimes.push_back(Elt: "cfi" ); |
| 1704 | if (SanArgs.needsCfiCrossDsoDiagRt()) |
| 1705 | StaticRuntimes.push_back(Elt: "cfi_diag" ); |
| 1706 | } |
| 1707 | if (SanArgs.linkCXXRuntimes() && !SanArgs.requiresMinimalRuntime() && |
| 1708 | ((!SanArgs.needsSharedRt() && SanArgs.needsUbsanCXXRt()) || |
| 1709 | SanArgs.needsCfiCrossDsoDiagRt())) { |
| 1710 | StaticRuntimes.push_back(Elt: "ubsan_standalone_cxx" ); |
| 1711 | } |
| 1712 | if (SanArgs.needsStatsRt()) { |
| 1713 | NonWholeStaticRuntimes.push_back(Elt: "stats" ); |
| 1714 | RequiredSymbols.push_back(Elt: "__sanitizer_stats_register" ); |
| 1715 | } |
| 1716 | if (!SanArgs.needsSharedRt() && SanArgs.needsScudoRt()) { |
| 1717 | StaticRuntimes.push_back(Elt: "scudo_standalone" ); |
| 1718 | if (SanArgs.linkCXXRuntimes()) |
| 1719 | StaticRuntimes.push_back(Elt: "scudo_standalone_cxx" ); |
| 1720 | } |
| 1721 | } |
| 1722 | |
| 1723 | // Should be called before we add system libraries (C++ ABI, libstdc++/libc++, |
| 1724 | // C runtime, etc). Returns true if sanitizer system deps need to be linked in. |
| 1725 | bool tools::addSanitizerRuntimes(const ToolChain &TC, const ArgList &Args, |
| 1726 | ArgStringList &CmdArgs) { |
| 1727 | const SanitizerArgs &SanArgs = TC.getSanitizerArgs(JobArgs: Args); |
| 1728 | SmallVector<StringRef, 4> SharedRuntimes, StaticRuntimes, |
| 1729 | NonWholeStaticRuntimes, HelperStaticRuntimes, RequiredSymbols; |
| 1730 | if (SanArgs.linkRuntimes()) { |
| 1731 | collectSanitizerRuntimes(TC, Args, SharedRuntimes, StaticRuntimes, |
| 1732 | NonWholeStaticRuntimes, HelperStaticRuntimes, |
| 1733 | RequiredSymbols); |
| 1734 | } |
| 1735 | |
| 1736 | // -u options must be added before the runtime libs that resolve them. |
| 1737 | for (auto S : RequiredSymbols) { |
| 1738 | CmdArgs.push_back(Elt: "-u" ); |
| 1739 | CmdArgs.push_back(Elt: Args.MakeArgString(Str: S)); |
| 1740 | } |
| 1741 | |
| 1742 | // Inject libfuzzer dependencies. |
| 1743 | if (SanArgs.needsFuzzer() && SanArgs.linkRuntimes() && |
| 1744 | !Args.hasArg(Ids: options::OPT_shared)) { |
| 1745 | |
| 1746 | addSanitizerRuntime(TC, Args, CmdArgs, Sanitizer: "fuzzer" , IsShared: false, IsWhole: true); |
| 1747 | if (SanArgs.needsFuzzerInterceptors()) |
| 1748 | addSanitizerRuntime(TC, Args, CmdArgs, Sanitizer: "fuzzer_interceptors" , IsShared: false, |
| 1749 | IsWhole: true); |
| 1750 | if (!Args.hasArg(Ids: options::OPT_nostdlibxx)) { |
| 1751 | bool OnlyLibstdcxxStatic = Args.hasArg(Ids: options::OPT_static_libstdcxx) && |
| 1752 | !Args.hasArg(Ids: options::OPT_static); |
| 1753 | if (OnlyLibstdcxxStatic) |
| 1754 | CmdArgs.push_back(Elt: "-Bstatic" ); |
| 1755 | TC.AddCXXStdlibLibArgs(Args, CmdArgs); |
| 1756 | if (OnlyLibstdcxxStatic) |
| 1757 | CmdArgs.push_back(Elt: "-Bdynamic" ); |
| 1758 | } |
| 1759 | } |
| 1760 | |
| 1761 | for (auto RT : SharedRuntimes) |
| 1762 | addSanitizerRuntime(TC, Args, CmdArgs, Sanitizer: RT, IsShared: true, IsWhole: false); |
| 1763 | for (auto RT : HelperStaticRuntimes) |
| 1764 | addSanitizerRuntime(TC, Args, CmdArgs, Sanitizer: RT, IsShared: false, IsWhole: true); |
| 1765 | bool AddExportDynamic = false; |
| 1766 | for (auto RT : StaticRuntimes) { |
| 1767 | addSanitizerRuntime(TC, Args, CmdArgs, Sanitizer: RT, IsShared: false, IsWhole: true); |
| 1768 | AddExportDynamic |= !addSanitizerDynamicList(TC, Args, CmdArgs, Sanitizer: RT); |
| 1769 | } |
| 1770 | for (auto RT : NonWholeStaticRuntimes) { |
| 1771 | addSanitizerRuntime(TC, Args, CmdArgs, Sanitizer: RT, IsShared: false, IsWhole: false); |
| 1772 | AddExportDynamic |= !addSanitizerDynamicList(TC, Args, CmdArgs, Sanitizer: RT); |
| 1773 | } |
| 1774 | // If there is a static runtime with no dynamic list, force all the symbols |
| 1775 | // to be dynamic to be sure we export sanitizer interface functions. |
| 1776 | if (AddExportDynamic) |
| 1777 | CmdArgs.push_back(Elt: "--export-dynamic" ); |
| 1778 | |
| 1779 | if (SanArgs.hasCrossDsoCfi() && !AddExportDynamic) |
| 1780 | CmdArgs.push_back(Elt: "--export-dynamic-symbol=__cfi_check" ); |
| 1781 | |
| 1782 | if (SanArgs.hasMemTag()) { |
| 1783 | if (!TC.getTriple().isAndroid()) { |
| 1784 | TC.getDriver().Diag(DiagID: diag::err_drv_unsupported_opt_for_target) |
| 1785 | << "-fsanitize=memtag*" << TC.getTriple().str(); |
| 1786 | } |
| 1787 | CmdArgs.push_back( |
| 1788 | Elt: Args.MakeArgString(Str: "--android-memtag-mode=" + SanArgs.getMemtagMode())); |
| 1789 | if (SanArgs.hasMemtagHeap()) |
| 1790 | CmdArgs.push_back(Elt: "--android-memtag-heap" ); |
| 1791 | if (SanArgs.hasMemtagStack()) |
| 1792 | CmdArgs.push_back(Elt: "--android-memtag-stack" ); |
| 1793 | } |
| 1794 | |
| 1795 | return !StaticRuntimes.empty() || !NonWholeStaticRuntimes.empty(); |
| 1796 | } |
| 1797 | |
| 1798 | bool tools::addXRayRuntime(const ToolChain&TC, const ArgList &Args, ArgStringList &CmdArgs) { |
| 1799 | const XRayArgs &XRay = TC.getXRayArgs(Args); |
| 1800 | if (Args.hasArg(Ids: options::OPT_shared)) { |
| 1801 | if (XRay.needsXRayDSORt()) { |
| 1802 | CmdArgs.push_back(Elt: "--whole-archive" ); |
| 1803 | CmdArgs.push_back(Elt: TC.getCompilerRTArgString(Args, Component: "xray-dso" )); |
| 1804 | CmdArgs.push_back(Elt: "--no-whole-archive" ); |
| 1805 | return true; |
| 1806 | } |
| 1807 | } else if (XRay.needsXRayRt()) { |
| 1808 | CmdArgs.push_back(Elt: "--whole-archive" ); |
| 1809 | CmdArgs.push_back(Elt: TC.getCompilerRTArgString(Args, Component: "xray" )); |
| 1810 | for (const auto &Mode : XRay.modeList()) |
| 1811 | CmdArgs.push_back(Elt: TC.getCompilerRTArgString(Args, Component: Mode)); |
| 1812 | CmdArgs.push_back(Elt: "--no-whole-archive" ); |
| 1813 | return true; |
| 1814 | } |
| 1815 | |
| 1816 | return false; |
| 1817 | } |
| 1818 | |
| 1819 | void tools::linkXRayRuntimeDeps(const ToolChain &TC, |
| 1820 | const llvm::opt::ArgList &Args, |
| 1821 | ArgStringList &CmdArgs) { |
| 1822 | addAsNeededOption(TC, Args, CmdArgs, as_needed: false); |
| 1823 | CmdArgs.push_back(Elt: "-lpthread" ); |
| 1824 | if (!TC.getTriple().isOSOpenBSD()) |
| 1825 | CmdArgs.push_back(Elt: "-lrt" ); |
| 1826 | CmdArgs.push_back(Elt: "-lm" ); |
| 1827 | |
| 1828 | if (!TC.getTriple().isOSFreeBSD() && |
| 1829 | !TC.getTriple().isOSNetBSD() && |
| 1830 | !TC.getTriple().isOSOpenBSD()) |
| 1831 | CmdArgs.push_back(Elt: "-ldl" ); |
| 1832 | } |
| 1833 | |
| 1834 | bool tools::areOptimizationsEnabled(const ArgList &Args) { |
| 1835 | // Find the last -O arg and see if it is non-zero. |
| 1836 | if (Arg *A = Args.getLastArg(Ids: options::OPT_O_Group)) |
| 1837 | return !A->getOption().matches(ID: options::OPT_O0); |
| 1838 | // Defaults to -O0. |
| 1839 | return false; |
| 1840 | } |
| 1841 | |
| 1842 | const char *tools::SplitDebugName(const JobAction &JA, const ArgList &Args, |
| 1843 | const InputInfo &Input, |
| 1844 | const InputInfo &Output) { |
| 1845 | auto AddPostfix = [JA](auto &F) { |
| 1846 | if (JA.getOffloadingDeviceKind() == Action::OFK_HIP) |
| 1847 | F += (Twine("_" ) + JA.getOffloadingArch()).str(); |
| 1848 | F += ".dwo" ; |
| 1849 | }; |
| 1850 | if (Arg *A = Args.getLastArg(Ids: options::OPT_gsplit_dwarf_EQ)) |
| 1851 | if (StringRef(A->getValue()) == "single" && Output.isFilename()) |
| 1852 | return Args.MakeArgString(Str: Output.getFilename()); |
| 1853 | |
| 1854 | SmallString<128> T; |
| 1855 | if (const Arg *A = Args.getLastArg(Ids: options::OPT_dumpdir)) { |
| 1856 | T = A->getValue(); |
| 1857 | } else { |
| 1858 | Arg *FinalOutput = Args.getLastArg(Ids: options::OPT_o, Ids: options::OPT__SLASH_o); |
| 1859 | if (FinalOutput && Args.hasArg(Ids: options::OPT_c)) { |
| 1860 | T = FinalOutput->getValue(); |
| 1861 | llvm::sys::path::remove_filename(path&: T); |
| 1862 | llvm::sys::path::append(path&: T, |
| 1863 | a: llvm::sys::path::stem(path: FinalOutput->getValue())); |
| 1864 | AddPostfix(T); |
| 1865 | return Args.MakeArgString(Str: T); |
| 1866 | } |
| 1867 | } |
| 1868 | |
| 1869 | T += llvm::sys::path::stem(path: Input.getBaseInput()); |
| 1870 | AddPostfix(T); |
| 1871 | return Args.MakeArgString(Str: T); |
| 1872 | } |
| 1873 | |
| 1874 | void tools::SplitDebugInfo(const ToolChain &TC, Compilation &C, const Tool &T, |
| 1875 | const JobAction &JA, const ArgList &Args, |
| 1876 | const InputInfo &Output, const char *OutFile) { |
| 1877 | ArgStringList ; |
| 1878 | ExtractArgs.push_back(Elt: "--extract-dwo" ); |
| 1879 | |
| 1880 | ArgStringList StripArgs; |
| 1881 | StripArgs.push_back(Elt: "--strip-dwo" ); |
| 1882 | |
| 1883 | // Grabbing the output of the earlier compile step. |
| 1884 | StripArgs.push_back(Elt: Output.getFilename()); |
| 1885 | ExtractArgs.push_back(Elt: Output.getFilename()); |
| 1886 | ExtractArgs.push_back(Elt: OutFile); |
| 1887 | |
| 1888 | const char *Exec = |
| 1889 | Args.MakeArgString(Str: TC.GetProgramPath(CLANG_DEFAULT_OBJCOPY)); |
| 1890 | InputInfo II(types::TY_Object, Output.getFilename(), Output.getFilename()); |
| 1891 | |
| 1892 | // First extract the dwo sections. |
| 1893 | C.addCommand(C: std::make_unique<Command>(args: JA, args: T, |
| 1894 | args: ResponseFileSupport::AtFileCurCP(), |
| 1895 | args&: Exec, args&: ExtractArgs, args&: II, args: Output)); |
| 1896 | |
| 1897 | // Then remove them from the original .o file. |
| 1898 | C.addCommand(C: std::make_unique<Command>( |
| 1899 | args: JA, args: T, args: ResponseFileSupport::AtFileCurCP(), args&: Exec, args&: StripArgs, args&: II, args: Output)); |
| 1900 | } |
| 1901 | |
| 1902 | // Claim options we don't want to warn if they are unused. We do this for |
| 1903 | // options that build systems might add but are unused when assembling or only |
| 1904 | // running the preprocessor for example. |
| 1905 | void tools::claimNoWarnArgs(const ArgList &Args) { |
| 1906 | // Don't warn about unused -f(no-)?lto. This can happen when we're |
| 1907 | // preprocessing, precompiling or assembling. |
| 1908 | Args.ClaimAllArgs(Id0: options::OPT_flto_EQ); |
| 1909 | Args.ClaimAllArgs(Id0: options::OPT_flto); |
| 1910 | Args.ClaimAllArgs(Id0: options::OPT_fno_lto); |
| 1911 | } |
| 1912 | |
| 1913 | Arg *tools::getLastCSProfileGenerateArg(const ArgList &Args) { |
| 1914 | auto *CSPGOGenerateArg = Args.getLastArg(Ids: options::OPT_fcs_profile_generate, |
| 1915 | Ids: options::OPT_fcs_profile_generate_EQ, |
| 1916 | Ids: options::OPT_fno_profile_generate); |
| 1917 | if (CSPGOGenerateArg && |
| 1918 | CSPGOGenerateArg->getOption().matches(ID: options::OPT_fno_profile_generate)) |
| 1919 | CSPGOGenerateArg = nullptr; |
| 1920 | |
| 1921 | return CSPGOGenerateArg; |
| 1922 | } |
| 1923 | |
| 1924 | Arg *tools::getLastProfileUseArg(const ArgList &Args) { |
| 1925 | auto *ProfileUseArg = Args.getLastArg( |
| 1926 | Ids: options::OPT_fprofile_instr_use, Ids: options::OPT_fprofile_instr_use_EQ, |
| 1927 | Ids: options::OPT_fprofile_use, Ids: options::OPT_fprofile_use_EQ, |
| 1928 | Ids: options::OPT_fno_profile_instr_use); |
| 1929 | |
| 1930 | if (ProfileUseArg && |
| 1931 | ProfileUseArg->getOption().matches(ID: options::OPT_fno_profile_instr_use)) |
| 1932 | ProfileUseArg = nullptr; |
| 1933 | |
| 1934 | return ProfileUseArg; |
| 1935 | } |
| 1936 | |
| 1937 | Arg *tools::getLastProfileSampleUseArg(const ArgList &Args) { |
| 1938 | auto *ProfileSampleUseArg = Args.getLastArg( |
| 1939 | Ids: options::OPT_fprofile_sample_use_EQ, Ids: options::OPT_fno_profile_sample_use); |
| 1940 | |
| 1941 | if (ProfileSampleUseArg && (ProfileSampleUseArg->getOption().matches( |
| 1942 | ID: options::OPT_fno_profile_sample_use))) |
| 1943 | return nullptr; |
| 1944 | |
| 1945 | return Args.getLastArg(Ids: options::OPT_fprofile_sample_use_EQ); |
| 1946 | } |
| 1947 | |
| 1948 | const char *tools::RelocationModelName(llvm::Reloc::Model Model) { |
| 1949 | switch (Model) { |
| 1950 | case llvm::Reloc::Static: |
| 1951 | return "static" ; |
| 1952 | case llvm::Reloc::PIC_: |
| 1953 | return "pic" ; |
| 1954 | case llvm::Reloc::DynamicNoPIC: |
| 1955 | return "dynamic-no-pic" ; |
| 1956 | case llvm::Reloc::ROPI: |
| 1957 | return "ropi" ; |
| 1958 | case llvm::Reloc::RWPI: |
| 1959 | return "rwpi" ; |
| 1960 | case llvm::Reloc::ROPI_RWPI: |
| 1961 | return "ropi-rwpi" ; |
| 1962 | } |
| 1963 | llvm_unreachable("Unknown Reloc::Model kind" ); |
| 1964 | } |
| 1965 | |
| 1966 | /// Parses the various -fpic/-fPIC/-fpie/-fPIE arguments. Then, |
| 1967 | /// smooshes them together with platform defaults, to decide whether |
| 1968 | /// this compile should be using PIC mode or not. Returns a tuple of |
| 1969 | /// (RelocationModel, PICLevel, IsPIE). |
| 1970 | std::tuple<llvm::Reloc::Model, unsigned, bool> |
| 1971 | tools::ParsePICArgs(const ToolChain &ToolChain, const ArgList &Args) { |
| 1972 | const llvm::Triple &EffectiveTriple = ToolChain.getEffectiveTriple(); |
| 1973 | const llvm::Triple &Triple = ToolChain.getTriple(); |
| 1974 | |
| 1975 | bool PIE = ToolChain.isPIEDefault(Args); |
| 1976 | bool PIC = PIE || ToolChain.isPICDefault(); |
| 1977 | // The Darwin/MachO default to use PIC does not apply when using -static. |
| 1978 | if (Triple.isOSBinFormatMachO() && Args.hasArg(Ids: options::OPT_static)) |
| 1979 | PIE = PIC = false; |
| 1980 | bool IsPICLevelTwo = PIC; |
| 1981 | |
| 1982 | bool KernelOrKext = |
| 1983 | Args.hasArg(Ids: options::OPT_mkernel, Ids: options::OPT_fapple_kext); |
| 1984 | |
| 1985 | // Android-specific defaults for PIC/PIE |
| 1986 | if (Triple.isAndroid()) { |
| 1987 | switch (Triple.getArch()) { |
| 1988 | case llvm::Triple::x86: |
| 1989 | case llvm::Triple::x86_64: |
| 1990 | PIC = true; // "-fPIC" |
| 1991 | IsPICLevelTwo = true; |
| 1992 | break; |
| 1993 | |
| 1994 | default: |
| 1995 | PIC = true; // "-fpic" |
| 1996 | break; |
| 1997 | } |
| 1998 | } |
| 1999 | |
| 2000 | // OHOS-specific defaults for PIC/PIE |
| 2001 | if (Triple.isOHOSFamily() && Triple.getArch() == llvm::Triple::aarch64) |
| 2002 | PIC = true; |
| 2003 | |
| 2004 | // OpenBSD-specific defaults for PIE |
| 2005 | if (Triple.isOSOpenBSD()) { |
| 2006 | switch (ToolChain.getArch()) { |
| 2007 | case llvm::Triple::arm: |
| 2008 | case llvm::Triple::aarch64: |
| 2009 | case llvm::Triple::mips64: |
| 2010 | case llvm::Triple::mips64el: |
| 2011 | case llvm::Triple::x86: |
| 2012 | case llvm::Triple::x86_64: |
| 2013 | IsPICLevelTwo = false; // "-fpie" |
| 2014 | break; |
| 2015 | |
| 2016 | case llvm::Triple::ppc: |
| 2017 | case llvm::Triple::sparcv9: |
| 2018 | IsPICLevelTwo = true; // "-fPIE" |
| 2019 | break; |
| 2020 | |
| 2021 | default: |
| 2022 | break; |
| 2023 | } |
| 2024 | } |
| 2025 | |
| 2026 | // The last argument relating to either PIC or PIE wins, and no |
| 2027 | // other argument is used. If the last argument is any flavor of the |
| 2028 | // '-fno-...' arguments, both PIC and PIE are disabled. Any PIE |
| 2029 | // option implicitly enables PIC at the same level. |
| 2030 | Arg *LastPICArg = Args.getLastArg(Ids: options::OPT_fPIC, Ids: options::OPT_fno_PIC, |
| 2031 | Ids: options::OPT_fpic, Ids: options::OPT_fno_pic, |
| 2032 | Ids: options::OPT_fPIE, Ids: options::OPT_fno_PIE, |
| 2033 | Ids: options::OPT_fpie, Ids: options::OPT_fno_pie); |
| 2034 | if (Triple.isOSWindows() && !Triple.isOSCygMing() && LastPICArg && |
| 2035 | LastPICArg == Args.getLastArg(Ids: options::OPT_fPIC, Ids: options::OPT_fpic, |
| 2036 | Ids: options::OPT_fPIE, Ids: options::OPT_fpie)) { |
| 2037 | ToolChain.getDriver().Diag(DiagID: diag::err_drv_unsupported_opt_for_target) |
| 2038 | << LastPICArg->getSpelling() << Triple.str(); |
| 2039 | if (Triple.getArch() == llvm::Triple::x86_64) |
| 2040 | return std::make_tuple(args: llvm::Reloc::PIC_, args: 2U, args: false); |
| 2041 | return std::make_tuple(args: llvm::Reloc::Static, args: 0U, args: false); |
| 2042 | } |
| 2043 | |
| 2044 | // Check whether the tool chain trumps the PIC-ness decision. If the PIC-ness |
| 2045 | // is forced, then neither PIC nor PIE flags will have no effect. |
| 2046 | if (!ToolChain.isPICDefaultForced()) { |
| 2047 | if (LastPICArg) { |
| 2048 | Option O = LastPICArg->getOption(); |
| 2049 | if (O.matches(ID: options::OPT_fPIC) || O.matches(ID: options::OPT_fpic) || |
| 2050 | O.matches(ID: options::OPT_fPIE) || O.matches(ID: options::OPT_fpie)) { |
| 2051 | PIE = O.matches(ID: options::OPT_fPIE) || O.matches(ID: options::OPT_fpie); |
| 2052 | PIC = |
| 2053 | PIE || O.matches(ID: options::OPT_fPIC) || O.matches(ID: options::OPT_fpic); |
| 2054 | IsPICLevelTwo = |
| 2055 | O.matches(ID: options::OPT_fPIE) || O.matches(ID: options::OPT_fPIC); |
| 2056 | } else { |
| 2057 | PIE = PIC = false; |
| 2058 | if (EffectiveTriple.isPS()) { |
| 2059 | Arg *ModelArg = Args.getLastArg(Ids: options::OPT_mcmodel_EQ); |
| 2060 | StringRef Model = ModelArg ? ModelArg->getValue() : "" ; |
| 2061 | if (Model != "kernel" ) { |
| 2062 | PIC = true; |
| 2063 | ToolChain.getDriver().Diag(DiagID: diag::warn_drv_ps_force_pic) |
| 2064 | << LastPICArg->getSpelling() |
| 2065 | << (EffectiveTriple.isPS4() ? "PS4" : "PS5" ); |
| 2066 | } |
| 2067 | } |
| 2068 | } |
| 2069 | } |
| 2070 | } |
| 2071 | |
| 2072 | // Introduce a Darwin and PS4/PS5-specific hack. If the default is PIC, but |
| 2073 | // the PIC level would've been set to level 1, force it back to level 2 PIC |
| 2074 | // instead. |
| 2075 | if (PIC && (Triple.isOSDarwin() || EffectiveTriple.isPS())) |
| 2076 | IsPICLevelTwo |= ToolChain.isPICDefault(); |
| 2077 | |
| 2078 | // This kernel flags are a trump-card: they will disable PIC/PIE |
| 2079 | // generation, independent of the argument order. |
| 2080 | if (KernelOrKext && |
| 2081 | ((!EffectiveTriple.isiOS() || EffectiveTriple.isOSVersionLT(Major: 6)) && |
| 2082 | !EffectiveTriple.isWatchOS() && !EffectiveTriple.isDriverKit())) |
| 2083 | PIC = PIE = false; |
| 2084 | |
| 2085 | if (Arg *A = Args.getLastArg(Ids: options::OPT_mdynamic_no_pic)) { |
| 2086 | // This is a very special mode. It trumps the other modes, almost no one |
| 2087 | // uses it, and it isn't even valid on any OS but Darwin. |
| 2088 | if (!Triple.isOSDarwin()) |
| 2089 | ToolChain.getDriver().Diag(DiagID: diag::err_drv_unsupported_opt_for_target) |
| 2090 | << A->getSpelling() << Triple.str(); |
| 2091 | |
| 2092 | // FIXME: Warn when this flag trumps some other PIC or PIE flag. |
| 2093 | |
| 2094 | // Only a forced PIC mode can cause the actual compile to have PIC defines |
| 2095 | // etc., no flags are sufficient. This behavior was selected to closely |
| 2096 | // match that of llvm-gcc and Apple GCC before that. |
| 2097 | PIC = ToolChain.isPICDefault() && ToolChain.isPICDefaultForced(); |
| 2098 | |
| 2099 | return std::make_tuple(args: llvm::Reloc::DynamicNoPIC, args: PIC ? 2U : 0U, args: false); |
| 2100 | } |
| 2101 | |
| 2102 | bool EmbeddedPISupported; |
| 2103 | switch (Triple.getArch()) { |
| 2104 | case llvm::Triple::arm: |
| 2105 | case llvm::Triple::armeb: |
| 2106 | case llvm::Triple::thumb: |
| 2107 | case llvm::Triple::thumbeb: |
| 2108 | EmbeddedPISupported = true; |
| 2109 | break; |
| 2110 | default: |
| 2111 | EmbeddedPISupported = false; |
| 2112 | break; |
| 2113 | } |
| 2114 | |
| 2115 | bool ROPI = false, RWPI = false; |
| 2116 | Arg* LastROPIArg = Args.getLastArg(Ids: options::OPT_fropi, Ids: options::OPT_fno_ropi); |
| 2117 | if (LastROPIArg && LastROPIArg->getOption().matches(ID: options::OPT_fropi)) { |
| 2118 | if (!EmbeddedPISupported) |
| 2119 | ToolChain.getDriver().Diag(DiagID: diag::err_drv_unsupported_opt_for_target) |
| 2120 | << LastROPIArg->getSpelling() << Triple.str(); |
| 2121 | ROPI = true; |
| 2122 | } |
| 2123 | Arg *LastRWPIArg = Args.getLastArg(Ids: options::OPT_frwpi, Ids: options::OPT_fno_rwpi); |
| 2124 | if (LastRWPIArg && LastRWPIArg->getOption().matches(ID: options::OPT_frwpi)) { |
| 2125 | if (!EmbeddedPISupported) |
| 2126 | ToolChain.getDriver().Diag(DiagID: diag::err_drv_unsupported_opt_for_target) |
| 2127 | << LastRWPIArg->getSpelling() << Triple.str(); |
| 2128 | RWPI = true; |
| 2129 | } |
| 2130 | |
| 2131 | // ROPI and RWPI are not compatible with PIC or PIE. |
| 2132 | if ((ROPI || RWPI) && (PIC || PIE)) |
| 2133 | ToolChain.getDriver().Diag(DiagID: diag::err_drv_ropi_rwpi_incompatible_with_pic); |
| 2134 | |
| 2135 | if (Triple.isMIPS()) { |
| 2136 | StringRef CPUName; |
| 2137 | StringRef ABIName; |
| 2138 | mips::getMipsCPUAndABI(Args, Triple, CPUName, ABIName); |
| 2139 | // When targeting the N64 ABI, PIC is the default, except in the case |
| 2140 | // when the -mno-abicalls option is used. In that case we exit |
| 2141 | // at next check regardless of PIC being set below. |
| 2142 | if (ABIName == "n64" ) |
| 2143 | PIC = true; |
| 2144 | // When targettng MIPS with -mno-abicalls, it's always static. |
| 2145 | if(Args.hasArg(Ids: options::OPT_mno_abicalls)) |
| 2146 | return std::make_tuple(args: llvm::Reloc::Static, args: 0U, args: false); |
| 2147 | // Unlike other architectures, MIPS, even with -fPIC/-mxgot/multigot, |
| 2148 | // does not use PIC level 2 for historical reasons. |
| 2149 | IsPICLevelTwo = false; |
| 2150 | } |
| 2151 | |
| 2152 | if (PIC) |
| 2153 | return std::make_tuple(args: llvm::Reloc::PIC_, args: IsPICLevelTwo ? 2U : 1U, args&: PIE); |
| 2154 | |
| 2155 | llvm::Reloc::Model RelocM = llvm::Reloc::Static; |
| 2156 | if (ROPI && RWPI) |
| 2157 | RelocM = llvm::Reloc::ROPI_RWPI; |
| 2158 | else if (ROPI) |
| 2159 | RelocM = llvm::Reloc::ROPI; |
| 2160 | else if (RWPI) |
| 2161 | RelocM = llvm::Reloc::RWPI; |
| 2162 | |
| 2163 | return std::make_tuple(args&: RelocM, args: 0U, args: false); |
| 2164 | } |
| 2165 | |
| 2166 | bool tools::getStaticPIE(const ArgList &Args, const ToolChain &TC) { |
| 2167 | bool HasStaticPIE = Args.hasArg(Ids: options::OPT_static_pie); |
| 2168 | if (HasStaticPIE && Args.hasArg(Ids: options::OPT_no_pie)) { |
| 2169 | const Driver &D = TC.getDriver(); |
| 2170 | const llvm::opt::OptTable &Opts = D.getOpts(); |
| 2171 | StringRef StaticPIEName = Opts.getOptionName(id: options::OPT_static_pie); |
| 2172 | StringRef NoPIEName = Opts.getOptionName(id: options::OPT_nopie); |
| 2173 | D.Diag(DiagID: diag::err_drv_cannot_mix_options) << StaticPIEName << NoPIEName; |
| 2174 | } |
| 2175 | return HasStaticPIE; |
| 2176 | } |
| 2177 | |
| 2178 | // `-falign-functions` indicates that the functions should be aligned to the |
| 2179 | // backend's preferred alignment. |
| 2180 | // |
| 2181 | // `-falign-functions=1` is the same as `-fno-align-functions`. |
| 2182 | // |
| 2183 | // The scalar `n` in `-falign-functions=n` must be an integral value between |
| 2184 | // [0, 65536]. If the value is not a power-of-two, it will be rounded up to |
| 2185 | // the nearest power-of-two. |
| 2186 | // |
| 2187 | // If we return `0`, the frontend will default to the backend's preferred |
| 2188 | // alignment. |
| 2189 | // |
| 2190 | // NOTE: icc only allows values between [0, 4096]. icc uses `-falign-functions` |
| 2191 | // to mean `-falign-functions=16`. GCC defaults to the backend's preferred |
| 2192 | // alignment. For unaligned functions, we default to the backend's preferred |
| 2193 | // alignment. |
| 2194 | unsigned tools::ParseFunctionAlignment(const ToolChain &TC, |
| 2195 | const ArgList &Args) { |
| 2196 | const Arg *A = Args.getLastArg(Ids: options::OPT_falign_functions, |
| 2197 | Ids: options::OPT_falign_functions_EQ, |
| 2198 | Ids: options::OPT_fno_align_functions); |
| 2199 | if (!A || A->getOption().matches(ID: options::OPT_fno_align_functions)) |
| 2200 | return 0; |
| 2201 | |
| 2202 | if (A->getOption().matches(ID: options::OPT_falign_functions)) |
| 2203 | return 0; |
| 2204 | |
| 2205 | unsigned Value = 0; |
| 2206 | if (StringRef(A->getValue()).getAsInteger(Radix: 10, Result&: Value) || Value > 65536) |
| 2207 | TC.getDriver().Diag(DiagID: diag::err_drv_invalid_int_value) |
| 2208 | << A->getAsString(Args) << A->getValue(); |
| 2209 | return Value ? llvm::Log2_32_Ceil(Value: std::min(a: Value, b: 65536u)) : Value; |
| 2210 | } |
| 2211 | |
| 2212 | void tools::addDebugInfoKind( |
| 2213 | ArgStringList &CmdArgs, llvm::codegenoptions::DebugInfoKind DebugInfoKind) { |
| 2214 | switch (DebugInfoKind) { |
| 2215 | case llvm::codegenoptions::DebugDirectivesOnly: |
| 2216 | CmdArgs.push_back(Elt: "-debug-info-kind=line-directives-only" ); |
| 2217 | break; |
| 2218 | case llvm::codegenoptions::DebugLineTablesOnly: |
| 2219 | CmdArgs.push_back(Elt: "-debug-info-kind=line-tables-only" ); |
| 2220 | break; |
| 2221 | case llvm::codegenoptions::DebugInfoConstructor: |
| 2222 | CmdArgs.push_back(Elt: "-debug-info-kind=constructor" ); |
| 2223 | break; |
| 2224 | case llvm::codegenoptions::LimitedDebugInfo: |
| 2225 | CmdArgs.push_back(Elt: "-debug-info-kind=limited" ); |
| 2226 | break; |
| 2227 | case llvm::codegenoptions::FullDebugInfo: |
| 2228 | CmdArgs.push_back(Elt: "-debug-info-kind=standalone" ); |
| 2229 | break; |
| 2230 | case llvm::codegenoptions::UnusedTypeInfo: |
| 2231 | CmdArgs.push_back(Elt: "-debug-info-kind=unused-types" ); |
| 2232 | break; |
| 2233 | default: |
| 2234 | break; |
| 2235 | } |
| 2236 | } |
| 2237 | |
| 2238 | // Convert an arg of the form "-gN" or "-ggdbN" or one of their aliases |
| 2239 | // to the corresponding DebugInfoKind. |
| 2240 | llvm::codegenoptions::DebugInfoKind tools::debugLevelToInfoKind(const Arg &A) { |
| 2241 | assert(A.getOption().matches(options::OPT_gN_Group) && |
| 2242 | "Not a -g option that specifies a debug-info level" ); |
| 2243 | if (A.getOption().matches(ID: options::OPT_g0) || |
| 2244 | A.getOption().matches(ID: options::OPT_ggdb0)) |
| 2245 | return llvm::codegenoptions::NoDebugInfo; |
| 2246 | if (A.getOption().matches(ID: options::OPT_gline_tables_only) || |
| 2247 | A.getOption().matches(ID: options::OPT_ggdb1)) |
| 2248 | return llvm::codegenoptions::DebugLineTablesOnly; |
| 2249 | if (A.getOption().matches(ID: options::OPT_gline_directives_only)) |
| 2250 | return llvm::codegenoptions::DebugDirectivesOnly; |
| 2251 | return llvm::codegenoptions::DebugInfoConstructor; |
| 2252 | } |
| 2253 | |
| 2254 | static unsigned ParseDebugDefaultVersion(const ToolChain &TC, |
| 2255 | const ArgList &Args) { |
| 2256 | const Arg *A = Args.getLastArg(Ids: options::OPT_fdebug_default_version); |
| 2257 | |
| 2258 | if (!A) |
| 2259 | return 0; |
| 2260 | |
| 2261 | unsigned Value = 0; |
| 2262 | if (StringRef(A->getValue()).getAsInteger(Radix: 10, Result&: Value) || Value > 6 || |
| 2263 | Value < 2) |
| 2264 | TC.getDriver().Diag(DiagID: diag::err_drv_invalid_int_value) |
| 2265 | << A->getAsString(Args) << A->getValue(); |
| 2266 | return Value; |
| 2267 | } |
| 2268 | |
| 2269 | unsigned tools::DwarfVersionNum(StringRef ArgValue) { |
| 2270 | return llvm::StringSwitch<unsigned>(ArgValue) |
| 2271 | .Case(S: "-gdwarf-2" , Value: 2) |
| 2272 | .Case(S: "-gdwarf-3" , Value: 3) |
| 2273 | .Case(S: "-gdwarf-4" , Value: 4) |
| 2274 | .Case(S: "-gdwarf-5" , Value: 5) |
| 2275 | .Case(S: "-gdwarf-6" , Value: 6) |
| 2276 | .Default(Value: 0); |
| 2277 | } |
| 2278 | |
| 2279 | const Arg *tools::getDwarfNArg(const ArgList &Args) { |
| 2280 | return Args.getLastArg(Ids: options::OPT_gdwarf_2, Ids: options::OPT_gdwarf_3, |
| 2281 | Ids: options::OPT_gdwarf_4, Ids: options::OPT_gdwarf_5, |
| 2282 | Ids: options::OPT_gdwarf_6, Ids: options::OPT_gdwarf); |
| 2283 | } |
| 2284 | |
| 2285 | unsigned tools::getDwarfVersion(const ToolChain &TC, |
| 2286 | const llvm::opt::ArgList &Args) { |
| 2287 | unsigned DwarfVersion = ParseDebugDefaultVersion(TC, Args); |
| 2288 | if (const Arg *GDwarfN = getDwarfNArg(Args)) |
| 2289 | if (int N = DwarfVersionNum(ArgValue: GDwarfN->getSpelling())) { |
| 2290 | DwarfVersion = N; |
| 2291 | if (DwarfVersion == 5 && TC.getTriple().isOSAIX()) |
| 2292 | TC.getDriver().Diag(DiagID: diag::err_drv_unsupported_opt_for_target) |
| 2293 | << GDwarfN->getSpelling() << TC.getTriple().str(); |
| 2294 | } |
| 2295 | if (DwarfVersion == 0) { |
| 2296 | DwarfVersion = TC.GetDefaultDwarfVersion(); |
| 2297 | assert(DwarfVersion && "toolchain default DWARF version must be nonzero" ); |
| 2298 | } |
| 2299 | return DwarfVersion; |
| 2300 | } |
| 2301 | |
| 2302 | DwarfFissionKind tools::getDebugFissionKind(const Driver &D, |
| 2303 | const ArgList &Args, Arg *&Arg) { |
| 2304 | Arg = Args.getLastArg(Ids: options::OPT_gsplit_dwarf, Ids: options::OPT_gsplit_dwarf_EQ, |
| 2305 | Ids: options::OPT_gno_split_dwarf); |
| 2306 | if (!Arg || Arg->getOption().matches(ID: options::OPT_gno_split_dwarf)) |
| 2307 | return DwarfFissionKind::None; |
| 2308 | |
| 2309 | if (Arg->getOption().matches(ID: options::OPT_gsplit_dwarf)) |
| 2310 | return DwarfFissionKind::Split; |
| 2311 | |
| 2312 | StringRef Value = Arg->getValue(); |
| 2313 | if (Value == "split" ) |
| 2314 | return DwarfFissionKind::Split; |
| 2315 | if (Value == "single" ) |
| 2316 | return DwarfFissionKind::Single; |
| 2317 | |
| 2318 | D.Diag(DiagID: diag::err_drv_unsupported_option_argument) |
| 2319 | << Arg->getSpelling() << Arg->getValue(); |
| 2320 | return DwarfFissionKind::None; |
| 2321 | } |
| 2322 | |
| 2323 | bool tools::checkDebugInfoOption(const Arg *A, const ArgList &Args, |
| 2324 | const Driver &D, const ToolChain &TC) { |
| 2325 | assert(A && "Expected non-nullptr argument." ); |
| 2326 | if (TC.supportsDebugInfoOption(A)) |
| 2327 | return true; |
| 2328 | D.Diag(DiagID: diag::warn_drv_unsupported_debug_info_opt_for_target) |
| 2329 | << A->getAsString(Args) << TC.getTripleString(); |
| 2330 | return false; |
| 2331 | } |
| 2332 | |
| 2333 | void tools::AddAssemblerKPIC(const ToolChain &ToolChain, const ArgList &Args, |
| 2334 | ArgStringList &CmdArgs) { |
| 2335 | llvm::Reloc::Model RelocationModel; |
| 2336 | unsigned PICLevel; |
| 2337 | bool IsPIE; |
| 2338 | std::tie(args&: RelocationModel, args&: PICLevel, args&: IsPIE) = ParsePICArgs(ToolChain, Args); |
| 2339 | |
| 2340 | if (RelocationModel != llvm::Reloc::Static) |
| 2341 | CmdArgs.push_back(Elt: "-KPIC" ); |
| 2342 | } |
| 2343 | |
| 2344 | /// Determine whether Objective-C automated reference counting is |
| 2345 | /// enabled. |
| 2346 | bool tools::isObjCAutoRefCount(const ArgList &Args) { |
| 2347 | return Args.hasFlag(Pos: options::OPT_fobjc_arc, Neg: options::OPT_fno_objc_arc, Default: false); |
| 2348 | } |
| 2349 | |
| 2350 | enum class LibGccType { UnspecifiedLibGcc, StaticLibGcc, SharedLibGcc }; |
| 2351 | |
| 2352 | static LibGccType getLibGccType(const ToolChain &TC, const Driver &D, |
| 2353 | const ArgList &Args) { |
| 2354 | if (Args.hasArg(Ids: options::OPT_static_libgcc) || |
| 2355 | Args.hasArg(Ids: options::OPT_static) || Args.hasArg(Ids: options::OPT_static_pie) || |
| 2356 | // The Android NDK only provides libunwind.a, not libunwind.so. |
| 2357 | TC.getTriple().isAndroid()) |
| 2358 | return LibGccType::StaticLibGcc; |
| 2359 | if (Args.hasArg(Ids: options::OPT_shared_libgcc)) |
| 2360 | return LibGccType::SharedLibGcc; |
| 2361 | return LibGccType::UnspecifiedLibGcc; |
| 2362 | } |
| 2363 | |
| 2364 | // Gcc adds libgcc arguments in various ways: |
| 2365 | // |
| 2366 | // gcc <none>: -lgcc --as-needed -lgcc_s --no-as-needed |
| 2367 | // g++ <none>: -lgcc_s -lgcc |
| 2368 | // gcc shared: -lgcc_s -lgcc |
| 2369 | // g++ shared: -lgcc_s -lgcc |
| 2370 | // gcc static: -lgcc -lgcc_eh |
| 2371 | // g++ static: -lgcc -lgcc_eh |
| 2372 | // gcc static-pie: -lgcc -lgcc_eh |
| 2373 | // g++ static-pie: -lgcc -lgcc_eh |
| 2374 | // |
| 2375 | // Also, certain targets need additional adjustments. |
| 2376 | |
| 2377 | static void AddUnwindLibrary(const ToolChain &TC, const Driver &D, |
| 2378 | ArgStringList &CmdArgs, const ArgList &Args) { |
| 2379 | ToolChain::UnwindLibType UNW = TC.GetUnwindLibType(Args); |
| 2380 | // By default OHOS binaries are linked statically to libunwind. |
| 2381 | if (TC.getTriple().isOHOSFamily() && UNW == ToolChain::UNW_CompilerRT) { |
| 2382 | CmdArgs.push_back(Elt: "-l:libunwind.a" ); |
| 2383 | return; |
| 2384 | } |
| 2385 | |
| 2386 | // Targets that don't use unwind libraries. |
| 2387 | if ((TC.getTriple().isAndroid() && UNW == ToolChain::UNW_Libgcc) || |
| 2388 | TC.getTriple().isOSIAMCU() || TC.getTriple().isOSBinFormatWasm() || |
| 2389 | TC.getTriple().isWindowsMSVCEnvironment() || UNW == ToolChain::UNW_None) |
| 2390 | return; |
| 2391 | |
| 2392 | LibGccType LGT = getLibGccType(TC, D, Args); |
| 2393 | bool AsNeeded = LGT == LibGccType::UnspecifiedLibGcc && |
| 2394 | (UNW == ToolChain::UNW_CompilerRT || !D.CCCIsCXX()) && |
| 2395 | !TC.getTriple().isAndroid() && |
| 2396 | !TC.getTriple().isOSCygMing() && !TC.getTriple().isOSAIX(); |
| 2397 | if (AsNeeded) |
| 2398 | addAsNeededOption(TC, Args, CmdArgs, as_needed: true); |
| 2399 | |
| 2400 | switch (UNW) { |
| 2401 | case ToolChain::UNW_None: |
| 2402 | return; |
| 2403 | case ToolChain::UNW_Libgcc: { |
| 2404 | if (LGT == LibGccType::StaticLibGcc) |
| 2405 | CmdArgs.push_back(Elt: "-lgcc_eh" ); |
| 2406 | else |
| 2407 | CmdArgs.push_back(Elt: "-lgcc_s" ); |
| 2408 | break; |
| 2409 | } |
| 2410 | case ToolChain::UNW_CompilerRT: |
| 2411 | if (TC.getTriple().isOSAIX()) { |
| 2412 | // AIX only has libunwind as a shared library. So do not pass |
| 2413 | // anything in if -static is specified. |
| 2414 | if (LGT != LibGccType::StaticLibGcc) |
| 2415 | CmdArgs.push_back(Elt: "-lunwind" ); |
| 2416 | } else if (LGT == LibGccType::StaticLibGcc) { |
| 2417 | CmdArgs.push_back(Elt: "-l:libunwind.a" ); |
| 2418 | } else if (LGT == LibGccType::SharedLibGcc) { |
| 2419 | if (TC.getTriple().isOSCygMing()) |
| 2420 | CmdArgs.push_back(Elt: "-l:libunwind.dll.a" ); |
| 2421 | else |
| 2422 | CmdArgs.push_back(Elt: "-l:libunwind.so" ); |
| 2423 | } else { |
| 2424 | // Let the linker choose between libunwind.so and libunwind.a |
| 2425 | // depending on what's available, and depending on the -static flag |
| 2426 | CmdArgs.push_back(Elt: "-lunwind" ); |
| 2427 | } |
| 2428 | break; |
| 2429 | } |
| 2430 | |
| 2431 | if (AsNeeded) |
| 2432 | addAsNeededOption(TC, Args, CmdArgs, as_needed: false); |
| 2433 | } |
| 2434 | |
| 2435 | static void AddLibgcc(const ToolChain &TC, const Driver &D, |
| 2436 | ArgStringList &CmdArgs, const ArgList &Args) { |
| 2437 | LibGccType LGT = getLibGccType(TC, D, Args); |
| 2438 | if (LGT == LibGccType::StaticLibGcc || |
| 2439 | (LGT == LibGccType::UnspecifiedLibGcc && !D.CCCIsCXX())) |
| 2440 | CmdArgs.push_back(Elt: "-lgcc" ); |
| 2441 | AddUnwindLibrary(TC, D, CmdArgs, Args); |
| 2442 | if (LGT == LibGccType::SharedLibGcc || |
| 2443 | (LGT == LibGccType::UnspecifiedLibGcc && D.CCCIsCXX())) |
| 2444 | CmdArgs.push_back(Elt: "-lgcc" ); |
| 2445 | // compiler-rt is needed after libgcc for flang on AArch64 for the |
| 2446 | // __trampoline_setup symbol |
| 2447 | if (D.IsFlangMode() && TC.getArch() == llvm::Triple::aarch64) { |
| 2448 | CmdArgs.push_back(Elt: "--as-needed" ); |
| 2449 | CmdArgs.push_back(Elt: TC.getCompilerRTArgString(Args, Component: "builtins" )); |
| 2450 | CmdArgs.push_back(Elt: "--no-as-needed" ); |
| 2451 | } |
| 2452 | } |
| 2453 | |
| 2454 | void tools::AddRunTimeLibs(const ToolChain &TC, const Driver &D, |
| 2455 | ArgStringList &CmdArgs, const ArgList &Args) { |
| 2456 | // Make use of compiler-rt if --rtlib option is used |
| 2457 | ToolChain::RuntimeLibType RLT = TC.GetRuntimeLibType(Args); |
| 2458 | |
| 2459 | switch (RLT) { |
| 2460 | case ToolChain::RLT_CompilerRT: |
| 2461 | CmdArgs.push_back(Elt: TC.getCompilerRTArgString(Args, Component: "builtins" )); |
| 2462 | AddUnwindLibrary(TC, D, CmdArgs, Args); |
| 2463 | break; |
| 2464 | case ToolChain::RLT_Libgcc: |
| 2465 | // Make sure libgcc is not used under MSVC environment by default |
| 2466 | if (TC.getTriple().isKnownWindowsMSVCEnvironment()) { |
| 2467 | // Issue error diagnostic if libgcc is explicitly specified |
| 2468 | // through command line as --rtlib option argument. |
| 2469 | Arg *A = Args.getLastArg(Ids: options::OPT_rtlib_EQ); |
| 2470 | if (A && A->getValue() != StringRef("platform" )) { |
| 2471 | TC.getDriver().Diag(DiagID: diag::err_drv_unsupported_rtlib_for_platform) |
| 2472 | << A->getValue() << "MSVC" ; |
| 2473 | } |
| 2474 | } else |
| 2475 | AddLibgcc(TC, D, CmdArgs, Args); |
| 2476 | break; |
| 2477 | } |
| 2478 | |
| 2479 | // On Android, the unwinder uses dl_iterate_phdr (or one of |
| 2480 | // dl_unwind_find_exidx/__gnu_Unwind_Find_exidx on arm32) from libdl.so. For |
| 2481 | // statically-linked executables, these functions come from libc.a instead. |
| 2482 | if (TC.getTriple().isAndroid() && !Args.hasArg(Ids: options::OPT_static) && |
| 2483 | !Args.hasArg(Ids: options::OPT_static_pie)) |
| 2484 | CmdArgs.push_back(Elt: "-ldl" ); |
| 2485 | } |
| 2486 | |
| 2487 | SmallString<128> tools::getStatsFileName(const llvm::opt::ArgList &Args, |
| 2488 | const InputInfo &Output, |
| 2489 | const InputInfo &Input, |
| 2490 | const Driver &D) { |
| 2491 | const Arg *A = Args.getLastArg(Ids: options::OPT_save_stats_EQ); |
| 2492 | if (!A && !D.CCPrintInternalStats) |
| 2493 | return {}; |
| 2494 | |
| 2495 | SmallString<128> StatsFile; |
| 2496 | if (A) { |
| 2497 | StringRef SaveStats = A->getValue(); |
| 2498 | if (SaveStats == "obj" && Output.isFilename()) { |
| 2499 | StatsFile.assign(RHS: Output.getFilename()); |
| 2500 | llvm::sys::path::remove_filename(path&: StatsFile); |
| 2501 | } else if (SaveStats != "cwd" ) { |
| 2502 | D.Diag(DiagID: diag::err_drv_invalid_value) << A->getAsString(Args) << SaveStats; |
| 2503 | return {}; |
| 2504 | } |
| 2505 | |
| 2506 | StringRef BaseName = llvm::sys::path::filename(path: Input.getBaseInput()); |
| 2507 | llvm::sys::path::append(path&: StatsFile, a: BaseName); |
| 2508 | llvm::sys::path::replace_extension(path&: StatsFile, extension: "stats" ); |
| 2509 | } else { |
| 2510 | assert(D.CCPrintInternalStats); |
| 2511 | StatsFile.assign(RHS: D.CCPrintInternalStatReportFilename.empty() |
| 2512 | ? "-" |
| 2513 | : D.CCPrintInternalStatReportFilename); |
| 2514 | } |
| 2515 | return StatsFile; |
| 2516 | } |
| 2517 | |
| 2518 | void tools::addMultilibFlag(bool Enabled, const StringRef Flag, |
| 2519 | Multilib::flags_list &Flags) { |
| 2520 | assert(Flag.front() == '-'); |
| 2521 | if (Enabled) { |
| 2522 | Flags.push_back(x: Flag.str()); |
| 2523 | } else { |
| 2524 | Flags.push_back(x: ("!" + Flag.substr(Start: 1)).str()); |
| 2525 | } |
| 2526 | } |
| 2527 | |
| 2528 | void tools::addX86AlignBranchArgs(const Driver &D, const ArgList &Args, |
| 2529 | ArgStringList &CmdArgs, bool IsLTO, |
| 2530 | const StringRef PluginOptPrefix) { |
| 2531 | auto addArg = [&, IsLTO](const Twine &Arg) { |
| 2532 | if (IsLTO) { |
| 2533 | assert(!PluginOptPrefix.empty() && "Cannot have empty PluginOptPrefix!" ); |
| 2534 | CmdArgs.push_back(Elt: Args.MakeArgString(Str: Twine(PluginOptPrefix) + Arg)); |
| 2535 | } else { |
| 2536 | CmdArgs.push_back(Elt: "-mllvm" ); |
| 2537 | CmdArgs.push_back(Elt: Args.MakeArgString(Str: Arg)); |
| 2538 | } |
| 2539 | }; |
| 2540 | |
| 2541 | if (Args.hasArg(Ids: options::OPT_mbranches_within_32B_boundaries)) { |
| 2542 | addArg(Twine("-x86-branches-within-32B-boundaries" )); |
| 2543 | } |
| 2544 | if (const Arg *A = Args.getLastArg(Ids: options::OPT_malign_branch_boundary_EQ)) { |
| 2545 | StringRef Value = A->getValue(); |
| 2546 | unsigned Boundary; |
| 2547 | if (Value.getAsInteger(Radix: 10, Result&: Boundary) || Boundary < 16 || |
| 2548 | !llvm::isPowerOf2_64(Value: Boundary)) { |
| 2549 | D.Diag(DiagID: diag::err_drv_invalid_argument_to_option) |
| 2550 | << Value << A->getOption().getName(); |
| 2551 | } else { |
| 2552 | addArg("-x86-align-branch-boundary=" + Twine(Boundary)); |
| 2553 | } |
| 2554 | } |
| 2555 | if (const Arg *A = Args.getLastArg(Ids: options::OPT_malign_branch_EQ)) { |
| 2556 | std::string AlignBranch; |
| 2557 | for (StringRef T : A->getValues()) { |
| 2558 | if (T != "fused" && T != "jcc" && T != "jmp" && T != "call" && |
| 2559 | T != "ret" && T != "indirect" ) |
| 2560 | D.Diag(DiagID: diag::err_drv_invalid_malign_branch_EQ) |
| 2561 | << T << "fused, jcc, jmp, call, ret, indirect" ; |
| 2562 | if (!AlignBranch.empty()) |
| 2563 | AlignBranch += '+'; |
| 2564 | AlignBranch += T; |
| 2565 | } |
| 2566 | addArg("-x86-align-branch=" + Twine(AlignBranch)); |
| 2567 | } |
| 2568 | if (const Arg *A = Args.getLastArg(Ids: options::OPT_mpad_max_prefix_size_EQ)) { |
| 2569 | StringRef Value = A->getValue(); |
| 2570 | unsigned PrefixSize; |
| 2571 | if (Value.getAsInteger(Radix: 10, Result&: PrefixSize)) { |
| 2572 | D.Diag(DiagID: diag::err_drv_invalid_argument_to_option) |
| 2573 | << Value << A->getOption().getName(); |
| 2574 | } else { |
| 2575 | addArg("-x86-pad-max-prefix-size=" + Twine(PrefixSize)); |
| 2576 | } |
| 2577 | } |
| 2578 | } |
| 2579 | |
| 2580 | /// SDLSearch: Search for Static Device Library |
| 2581 | /// The search for SDL bitcode files is consistent with how static host |
| 2582 | /// libraries are discovered. That is, the -l option triggers a search for |
| 2583 | /// files in a set of directories called the LINKPATH. The host library search |
| 2584 | /// procedure looks for a specific filename in the LINKPATH. The filename for |
| 2585 | /// a host library is lib<libname>.a or lib<libname>.so. For SDLs, there is an |
| 2586 | /// ordered-set of filenames that are searched. We call this ordered-set of |
| 2587 | /// filenames as SEARCH-ORDER. Since an SDL can either be device-type specific, |
| 2588 | /// architecture specific, or generic across all architectures, a naming |
| 2589 | /// convention and search order is used where the file name embeds the |
| 2590 | /// architecture name <arch-name> (nvptx or amdgcn) and the GPU device type |
| 2591 | /// <device-name> such as sm_30 and gfx906. <device-name> is absent in case of |
| 2592 | /// device-independent SDLs. To reduce congestion in host library directories, |
| 2593 | /// the search first looks for files in the “libdevice” subdirectory. SDLs that |
| 2594 | /// are bc files begin with the prefix “lib”. |
| 2595 | /// |
| 2596 | /// Machine-code SDLs can also be managed as an archive (*.a file). The |
| 2597 | /// convention has been to use the prefix “lib”. To avoid confusion with host |
| 2598 | /// archive libraries, we use prefix "libbc-" for the bitcode SDL archives. |
| 2599 | /// |
| 2600 | static bool SDLSearch(const Driver &D, const llvm::opt::ArgList &DriverArgs, |
| 2601 | llvm::opt::ArgStringList &CC1Args, |
| 2602 | const SmallVectorImpl<std::string> &LibraryPaths, |
| 2603 | StringRef Lib, StringRef Arch, StringRef Target, |
| 2604 | bool isBitCodeSDL) { |
| 2605 | SmallVector<std::string, 12> SDLs; |
| 2606 | |
| 2607 | std::string LibDeviceLoc = "/libdevice" ; |
| 2608 | std::string LibBcPrefix = "/libbc-" ; |
| 2609 | std::string LibPrefix = "/lib" ; |
| 2610 | |
| 2611 | if (isBitCodeSDL) { |
| 2612 | // SEARCH-ORDER for Bitcode SDLs: |
| 2613 | // libdevice/libbc-<libname>-<arch-name>-<device-type>.a |
| 2614 | // libbc-<libname>-<arch-name>-<device-type>.a |
| 2615 | // libdevice/libbc-<libname>-<arch-name>.a |
| 2616 | // libbc-<libname>-<arch-name>.a |
| 2617 | // libdevice/libbc-<libname>.a |
| 2618 | // libbc-<libname>.a |
| 2619 | // libdevice/lib<libname>-<arch-name>-<device-type>.bc |
| 2620 | // lib<libname>-<arch-name>-<device-type>.bc |
| 2621 | // libdevice/lib<libname>-<arch-name>.bc |
| 2622 | // lib<libname>-<arch-name>.bc |
| 2623 | // libdevice/lib<libname>.bc |
| 2624 | // lib<libname>.bc |
| 2625 | |
| 2626 | for (StringRef Base : {LibBcPrefix, LibPrefix}) { |
| 2627 | const auto *Ext = Base.contains(Other: LibBcPrefix) ? ".a" : ".bc" ; |
| 2628 | |
| 2629 | for (auto Suffix : {Twine(Lib + "-" + Arch + "-" + Target).str(), |
| 2630 | Twine(Lib + "-" + Arch).str(), Twine(Lib).str()}) { |
| 2631 | SDLs.push_back(Elt: Twine(LibDeviceLoc + Base + Suffix + Ext).str()); |
| 2632 | SDLs.push_back(Elt: Twine(Base + Suffix + Ext).str()); |
| 2633 | } |
| 2634 | } |
| 2635 | } else { |
| 2636 | // SEARCH-ORDER for Machine-code SDLs: |
| 2637 | // libdevice/lib<libname>-<arch-name>-<device-type>.a |
| 2638 | // lib<libname>-<arch-name>-<device-type>.a |
| 2639 | // libdevice/lib<libname>-<arch-name>.a |
| 2640 | // lib<libname>-<arch-name>.a |
| 2641 | |
| 2642 | const auto *Ext = ".a" ; |
| 2643 | |
| 2644 | for (auto Suffix : {Twine(Lib + "-" + Arch + "-" + Target).str(), |
| 2645 | Twine(Lib + "-" + Arch).str()}) { |
| 2646 | SDLs.push_back(Elt: Twine(LibDeviceLoc + LibPrefix + Suffix + Ext).str()); |
| 2647 | SDLs.push_back(Elt: Twine(LibPrefix + Suffix + Ext).str()); |
| 2648 | } |
| 2649 | } |
| 2650 | |
| 2651 | // The CUDA toolchain does not use a global device llvm-link before the LLVM |
| 2652 | // backend generates ptx. So currently, the use of bitcode SDL for nvptx is |
| 2653 | // only possible with post-clang-cc1 linking. Clang cc1 has a feature that |
| 2654 | // will link libraries after clang compilation while the LLVM IR is still in |
| 2655 | // memory. This utilizes a clang cc1 option called “-mlink-builtin-bitcode”. |
| 2656 | // This is a clang -cc1 option that is generated by the clang driver. The |
| 2657 | // option value must a full path to an existing file. |
| 2658 | bool FoundSDL = false; |
| 2659 | for (auto LPath : LibraryPaths) { |
| 2660 | for (auto SDL : SDLs) { |
| 2661 | auto FullName = Twine(LPath + SDL).str(); |
| 2662 | if (llvm::sys::fs::exists(Path: FullName)) { |
| 2663 | CC1Args.push_back(Elt: DriverArgs.MakeArgString(Str: FullName)); |
| 2664 | FoundSDL = true; |
| 2665 | break; |
| 2666 | } |
| 2667 | } |
| 2668 | if (FoundSDL) |
| 2669 | break; |
| 2670 | } |
| 2671 | return FoundSDL; |
| 2672 | } |
| 2673 | |
| 2674 | /// Search if a user provided archive file lib<libname>.a exists in any of |
| 2675 | /// the library paths. If so, add a new command to clang-offload-bundler to |
| 2676 | /// unbundle this archive and create a temporary device specific archive. Name |
| 2677 | /// of this SDL is passed to the llvm-link tool. |
| 2678 | static void GetSDLFromOffloadArchive( |
| 2679 | Compilation &C, const Driver &D, const Tool &T, const JobAction &JA, |
| 2680 | const InputInfoList &Inputs, const llvm::opt::ArgList &DriverArgs, |
| 2681 | llvm::opt::ArgStringList &CC1Args, |
| 2682 | const SmallVectorImpl<std::string> &LibraryPaths, StringRef Lib, |
| 2683 | StringRef Arch, StringRef Target, bool isBitCodeSDL) { |
| 2684 | |
| 2685 | // We don't support bitcode archive bundles for nvptx |
| 2686 | if (isBitCodeSDL && Arch.contains(Other: "nvptx" )) |
| 2687 | return; |
| 2688 | |
| 2689 | bool FoundAOB = false; |
| 2690 | std::string ArchiveOfBundles; |
| 2691 | |
| 2692 | llvm::Triple Triple(D.getTargetTriple()); |
| 2693 | bool IsMSVC = Triple.isWindowsMSVCEnvironment(); |
| 2694 | auto Ext = IsMSVC ? ".lib" : ".a" ; |
| 2695 | if (!Lib.starts_with(Prefix: ":" ) && !Lib.starts_with(Prefix: "-l" )) { |
| 2696 | if (llvm::sys::fs::exists(Path: Lib)) { |
| 2697 | ArchiveOfBundles = Lib; |
| 2698 | FoundAOB = true; |
| 2699 | } |
| 2700 | } else { |
| 2701 | Lib.consume_front(Prefix: "-l" ); |
| 2702 | for (auto LPath : LibraryPaths) { |
| 2703 | ArchiveOfBundles.clear(); |
| 2704 | auto LibFile = (Lib.starts_with(Prefix: ":" ) ? Lib.drop_front() |
| 2705 | : IsMSVC ? Lib + Ext |
| 2706 | : "lib" + Lib + Ext) |
| 2707 | .str(); |
| 2708 | for (auto Prefix : {"/libdevice/" , "/" }) { |
| 2709 | auto AOB = Twine(LPath + Prefix + LibFile).str(); |
| 2710 | if (llvm::sys::fs::exists(Path: AOB)) { |
| 2711 | ArchiveOfBundles = AOB; |
| 2712 | FoundAOB = true; |
| 2713 | break; |
| 2714 | } |
| 2715 | } |
| 2716 | if (FoundAOB) |
| 2717 | break; |
| 2718 | } |
| 2719 | } |
| 2720 | |
| 2721 | if (!FoundAOB) |
| 2722 | return; |
| 2723 | |
| 2724 | llvm::file_magic Magic; |
| 2725 | auto EC = llvm::identify_magic(path: ArchiveOfBundles, result&: Magic); |
| 2726 | if (EC || Magic != llvm::file_magic::archive) |
| 2727 | return; |
| 2728 | |
| 2729 | StringRef Prefix = isBitCodeSDL ? "libbc-" : "lib" ; |
| 2730 | std::string OutputLib = |
| 2731 | D.GetTemporaryPath(Prefix: Twine(Prefix + llvm::sys::path::filename(path: Lib) + "-" + |
| 2732 | Arch + "-" + Target) |
| 2733 | .str(), |
| 2734 | Suffix: "a" ); |
| 2735 | |
| 2736 | C.addTempFile(Name: C.getArgs().MakeArgString(Str: OutputLib)); |
| 2737 | |
| 2738 | SmallString<128> DeviceTriple; |
| 2739 | DeviceTriple += Action::GetOffloadKindName(Kind: JA.getOffloadingDeviceKind()); |
| 2740 | DeviceTriple += '-'; |
| 2741 | std::string NormalizedTriple = T.getToolChain().getTriple().normalize( |
| 2742 | Form: llvm::Triple::CanonicalForm::FOUR_IDENT); |
| 2743 | DeviceTriple += NormalizedTriple; |
| 2744 | if (!Target.empty()) { |
| 2745 | DeviceTriple += '-'; |
| 2746 | DeviceTriple += Target; |
| 2747 | } |
| 2748 | |
| 2749 | std::string UnbundleArg("-unbundle" ); |
| 2750 | std::string TypeArg("-type=a" ); |
| 2751 | std::string InputArg("-input=" + ArchiveOfBundles); |
| 2752 | std::string OffloadArg("-targets=" + std::string(DeviceTriple)); |
| 2753 | std::string OutputArg("-output=" + OutputLib); |
| 2754 | |
| 2755 | const char *UBProgram = DriverArgs.MakeArgString( |
| 2756 | Str: T.getToolChain().GetProgramPath(Name: "clang-offload-bundler" )); |
| 2757 | |
| 2758 | ArgStringList UBArgs; |
| 2759 | UBArgs.push_back(Elt: C.getArgs().MakeArgString(Str: UnbundleArg)); |
| 2760 | UBArgs.push_back(Elt: C.getArgs().MakeArgString(Str: TypeArg)); |
| 2761 | UBArgs.push_back(Elt: C.getArgs().MakeArgString(Str: InputArg)); |
| 2762 | UBArgs.push_back(Elt: C.getArgs().MakeArgString(Str: OffloadArg)); |
| 2763 | UBArgs.push_back(Elt: C.getArgs().MakeArgString(Str: OutputArg)); |
| 2764 | |
| 2765 | // Add this flag to not exit from clang-offload-bundler if no compatible |
| 2766 | // code object is found in heterogenous archive library. |
| 2767 | std::string AdditionalArgs("-allow-missing-bundles" ); |
| 2768 | UBArgs.push_back(Elt: C.getArgs().MakeArgString(Str: AdditionalArgs)); |
| 2769 | |
| 2770 | // Add this flag to treat hip and hipv4 offload kinds as compatible with |
| 2771 | // openmp offload kind while extracting code objects from a heterogenous |
| 2772 | // archive library. Vice versa is also considered compatible. |
| 2773 | std::string HipCompatibleArgs("-hip-openmp-compatible" ); |
| 2774 | UBArgs.push_back(Elt: C.getArgs().MakeArgString(Str: HipCompatibleArgs)); |
| 2775 | |
| 2776 | C.addCommand(C: std::make_unique<Command>( |
| 2777 | args: JA, args: T, args: ResponseFileSupport::AtFileCurCP(), args&: UBProgram, args&: UBArgs, args: Inputs, |
| 2778 | args: InputInfo(&JA, C.getArgs().MakeArgString(Str: OutputLib)))); |
| 2779 | |
| 2780 | CC1Args.push_back(Elt: DriverArgs.MakeArgString(Str: OutputLib)); |
| 2781 | } |
| 2782 | |
| 2783 | // Wrapper function used by driver for adding SDLs during link phase. |
| 2784 | void tools::AddStaticDeviceLibsLinking(Compilation &C, const Tool &T, |
| 2785 | const JobAction &JA, |
| 2786 | const InputInfoList &Inputs, |
| 2787 | const llvm::opt::ArgList &DriverArgs, |
| 2788 | llvm::opt::ArgStringList &CC1Args, |
| 2789 | StringRef Arch, StringRef Target, |
| 2790 | bool isBitCodeSDL) { |
| 2791 | AddStaticDeviceLibs(C: &C, T: &T, JA: &JA, Inputs: &Inputs, D: C.getDriver(), DriverArgs, CmdArgs&: CC1Args, |
| 2792 | Arch, Target, isBitCodeSDL); |
| 2793 | } |
| 2794 | |
| 2795 | // User defined Static Device Libraries(SDLs) can be passed to clang for |
| 2796 | // offloading GPU compilers. Like static host libraries, the use of a SDL is |
| 2797 | // specified with the -l command line option. The primary difference between |
| 2798 | // host and SDLs is the filenames for SDLs (refer SEARCH-ORDER for Bitcode SDLs |
| 2799 | // and SEARCH-ORDER for Machine-code SDLs for the naming convention). |
| 2800 | // SDLs are of following types: |
| 2801 | // |
| 2802 | // * Bitcode SDLs: They can either be a *.bc file or an archive of *.bc files. |
| 2803 | // For NVPTX, these libraries are post-clang linked following each |
| 2804 | // compilation. For AMDGPU, these libraries are linked one time |
| 2805 | // during the application link phase. |
| 2806 | // |
| 2807 | // * Machine-code SDLs: They are archive files. For AMDGPU, the process for |
| 2808 | // machine code SDLs is still in development. But they will be linked |
| 2809 | // by the LLVM tool lld. |
| 2810 | // |
| 2811 | // * Bundled objects that contain both host and device codes: Bundled objects |
| 2812 | // may also contain library code compiled from source. For NVPTX, the |
| 2813 | // bundle contains cubin. For AMDGPU, the bundle contains bitcode. |
| 2814 | // |
| 2815 | // For Bitcode and Machine-code SDLs, current compiler toolchains hardcode the |
| 2816 | // inclusion of specific SDLs such as math libraries and the OpenMP device |
| 2817 | // library libomptarget. |
| 2818 | void tools::AddStaticDeviceLibs(Compilation *C, const Tool *T, |
| 2819 | const JobAction *JA, |
| 2820 | const InputInfoList *Inputs, const Driver &D, |
| 2821 | const llvm::opt::ArgList &DriverArgs, |
| 2822 | llvm::opt::ArgStringList &CC1Args, |
| 2823 | StringRef Arch, StringRef Target, |
| 2824 | bool isBitCodeSDL) { |
| 2825 | |
| 2826 | SmallVector<std::string, 8> LibraryPaths; |
| 2827 | // Add search directories from LIBRARY_PATH env variable |
| 2828 | std::optional<std::string> LibPath = |
| 2829 | llvm::sys::Process::GetEnv(name: "LIBRARY_PATH" ); |
| 2830 | if (LibPath) { |
| 2831 | SmallVector<StringRef, 8> Frags; |
| 2832 | const char EnvPathSeparatorStr[] = {llvm::sys::EnvPathSeparator, '\0'}; |
| 2833 | llvm::SplitString(Source: *LibPath, OutFragments&: Frags, Delimiters: EnvPathSeparatorStr); |
| 2834 | for (StringRef Path : Frags) |
| 2835 | LibraryPaths.emplace_back(Args: Path.trim()); |
| 2836 | } |
| 2837 | |
| 2838 | // Add directories from user-specified -L options |
| 2839 | for (std::string Search_Dir : DriverArgs.getAllArgValues(Id: options::OPT_L)) |
| 2840 | LibraryPaths.emplace_back(Args&: Search_Dir); |
| 2841 | |
| 2842 | // Add path to lib-debug folders |
| 2843 | SmallString<256> DefaultLibPath = llvm::sys::path::parent_path(path: D.Dir); |
| 2844 | llvm::sys::path::append(path&: DefaultLibPath, CLANG_INSTALL_LIBDIR_BASENAME); |
| 2845 | LibraryPaths.emplace_back(Args: DefaultLibPath.c_str()); |
| 2846 | |
| 2847 | // Build list of Static Device Libraries SDLs specified by -l option |
| 2848 | llvm::SmallSet<std::string, 16> SDLNames; |
| 2849 | static const StringRef HostOnlyArchives[] = { |
| 2850 | "omp" , "cudart" , "m" , "gcc" , "gcc_s" , "pthread" , "hip_hcc" }; |
| 2851 | for (auto SDLName : DriverArgs.getAllArgValues(Id: options::OPT_l)) { |
| 2852 | if (!llvm::is_contained(Range: HostOnlyArchives, Element: SDLName)) { |
| 2853 | SDLNames.insert(V: std::string("-l" ) + SDLName); |
| 2854 | } |
| 2855 | } |
| 2856 | |
| 2857 | for (auto Input : DriverArgs.getAllArgValues(Id: options::OPT_INPUT)) { |
| 2858 | auto FileName = StringRef(Input); |
| 2859 | // Clang treats any unknown file types as archives and passes them to the |
| 2860 | // linker. Files with extension 'lib' are classified as TY_Object by clang |
| 2861 | // but they are usually archives. It is OK if the file is not really an |
| 2862 | // archive since GetSDLFromOffloadArchive will check the magic of the file |
| 2863 | // and only unbundle it if it is really an archive. |
| 2864 | const StringRef LibFileExt = ".lib" ; |
| 2865 | if (!llvm::sys::path::has_extension(path: FileName) || |
| 2866 | types::lookupTypeForExtension( |
| 2867 | Ext: llvm::sys::path::extension(path: FileName).drop_front()) == |
| 2868 | types::TY_INVALID || |
| 2869 | llvm::sys::path::extension(path: FileName) == LibFileExt) |
| 2870 | SDLNames.insert(V: Input); |
| 2871 | } |
| 2872 | |
| 2873 | // The search stops as soon as an SDL file is found. The driver then provides |
| 2874 | // the full filename of the SDL to the llvm-link command. If no SDL is found |
| 2875 | // after searching each LINKPATH with SEARCH-ORDER, it is possible that an |
| 2876 | // archive file lib<libname>.a exists and may contain bundled object files. |
| 2877 | for (auto SDLName : SDLNames) { |
| 2878 | // This is the only call to SDLSearch |
| 2879 | if (!SDLSearch(D, DriverArgs, CC1Args, LibraryPaths, Lib: SDLName, Arch, Target, |
| 2880 | isBitCodeSDL)) { |
| 2881 | GetSDLFromOffloadArchive(C&: *C, D, T: *T, JA: *JA, Inputs: *Inputs, DriverArgs, CC1Args, |
| 2882 | LibraryPaths, Lib: SDLName, Arch, Target, |
| 2883 | isBitCodeSDL); |
| 2884 | } |
| 2885 | } |
| 2886 | } |
| 2887 | |
| 2888 | static llvm::opt::Arg * |
| 2889 | getAMDGPUCodeObjectArgument(const Driver &D, const llvm::opt::ArgList &Args) { |
| 2890 | return Args.getLastArg(Ids: options::OPT_mcode_object_version_EQ); |
| 2891 | } |
| 2892 | |
| 2893 | void tools::checkAMDGPUCodeObjectVersion(const Driver &D, |
| 2894 | const llvm::opt::ArgList &Args) { |
| 2895 | const unsigned MinCodeObjVer = 4; |
| 2896 | const unsigned MaxCodeObjVer = 6; |
| 2897 | |
| 2898 | if (auto *CodeObjArg = getAMDGPUCodeObjectArgument(D, Args)) { |
| 2899 | if (CodeObjArg->getOption().getID() == |
| 2900 | options::OPT_mcode_object_version_EQ) { |
| 2901 | unsigned CodeObjVer = MaxCodeObjVer; |
| 2902 | auto Remnant = |
| 2903 | StringRef(CodeObjArg->getValue()).getAsInteger(Radix: 0, Result&: CodeObjVer); |
| 2904 | if (Remnant || CodeObjVer < MinCodeObjVer || CodeObjVer > MaxCodeObjVer) |
| 2905 | D.Diag(DiagID: diag::err_drv_invalid_int_value) |
| 2906 | << CodeObjArg->getAsString(Args) << CodeObjArg->getValue(); |
| 2907 | } |
| 2908 | } |
| 2909 | } |
| 2910 | |
| 2911 | unsigned tools::getAMDGPUCodeObjectVersion(const Driver &D, |
| 2912 | const llvm::opt::ArgList &Args) { |
| 2913 | unsigned CodeObjVer = 6; // default |
| 2914 | if (auto *CodeObjArg = getAMDGPUCodeObjectArgument(D, Args)) |
| 2915 | StringRef(CodeObjArg->getValue()).getAsInteger(Radix: 0, Result&: CodeObjVer); |
| 2916 | return CodeObjVer; |
| 2917 | } |
| 2918 | |
| 2919 | bool tools::haveAMDGPUCodeObjectVersionArgument( |
| 2920 | const Driver &D, const llvm::opt::ArgList &Args) { |
| 2921 | return getAMDGPUCodeObjectArgument(D, Args) != nullptr; |
| 2922 | } |
| 2923 | |
| 2924 | void tools::addMachineOutlinerArgs(const Driver &D, |
| 2925 | const llvm::opt::ArgList &Args, |
| 2926 | llvm::opt::ArgStringList &CmdArgs, |
| 2927 | const llvm::Triple &Triple, bool IsLTO, |
| 2928 | const StringRef PluginOptPrefix) { |
| 2929 | auto addArg = [&, IsLTO](const Twine &Arg) { |
| 2930 | if (IsLTO) { |
| 2931 | assert(!PluginOptPrefix.empty() && "Cannot have empty PluginOptPrefix!" ); |
| 2932 | CmdArgs.push_back(Elt: Args.MakeArgString(Str: Twine(PluginOptPrefix) + Arg)); |
| 2933 | } else { |
| 2934 | CmdArgs.push_back(Elt: "-mllvm" ); |
| 2935 | CmdArgs.push_back(Elt: Args.MakeArgString(Str: Arg)); |
| 2936 | } |
| 2937 | }; |
| 2938 | |
| 2939 | if (Arg *A = Args.getLastArg(Ids: options::OPT_moutline, |
| 2940 | Ids: options::OPT_mno_outline)) { |
| 2941 | if (A->getOption().matches(ID: options::OPT_moutline)) { |
| 2942 | // We only support -moutline in AArch64 and ARM targets right now. If |
| 2943 | // we're not compiling for these, emit a warning and ignore the flag. |
| 2944 | // Otherwise, add the proper mllvm flags. |
| 2945 | if (!(Triple.isARM() || Triple.isThumb() || Triple.isAArch64())) { |
| 2946 | D.Diag(DiagID: diag::warn_drv_moutline_unsupported_opt) << Triple.getArchName(); |
| 2947 | } else { |
| 2948 | addArg(Twine("-enable-machine-outliner" )); |
| 2949 | } |
| 2950 | } else { |
| 2951 | // Disable all outlining behaviour. |
| 2952 | addArg(Twine("-enable-machine-outliner=never" )); |
| 2953 | } |
| 2954 | } |
| 2955 | |
| 2956 | auto *CodeGenDataGenArg = |
| 2957 | Args.getLastArg(Ids: options::OPT_fcodegen_data_generate_EQ); |
| 2958 | auto *CodeGenDataUseArg = Args.getLastArg(Ids: options::OPT_fcodegen_data_use_EQ); |
| 2959 | |
| 2960 | // We only allow one of them to be specified. |
| 2961 | if (CodeGenDataGenArg && CodeGenDataUseArg) |
| 2962 | D.Diag(DiagID: diag::err_drv_argument_not_allowed_with) |
| 2963 | << CodeGenDataGenArg->getAsString(Args) |
| 2964 | << CodeGenDataUseArg->getAsString(Args); |
| 2965 | |
| 2966 | // For codegen data gen, the output file is passed to the linker |
| 2967 | // while a boolean flag is passed to the LLVM backend. |
| 2968 | if (CodeGenDataGenArg) |
| 2969 | addArg(Twine("-codegen-data-generate" )); |
| 2970 | |
| 2971 | // For codegen data use, the input file is passed to the LLVM backend. |
| 2972 | if (CodeGenDataUseArg) |
| 2973 | addArg(Twine("-codegen-data-use-path=" ) + CodeGenDataUseArg->getValue()); |
| 2974 | } |
| 2975 | |
| 2976 | void tools::addOpenMPDeviceRTL(const Driver &D, |
| 2977 | const llvm::opt::ArgList &DriverArgs, |
| 2978 | llvm::opt::ArgStringList &CC1Args, |
| 2979 | StringRef BitcodeSuffix, |
| 2980 | const llvm::Triple &Triple, |
| 2981 | const ToolChain &HostTC) { |
| 2982 | SmallVector<StringRef, 8> LibraryPaths; |
| 2983 | |
| 2984 | // Add user defined library paths from LIBRARY_PATH. |
| 2985 | std::optional<std::string> LibPath = |
| 2986 | llvm::sys::Process::GetEnv(name: "LIBRARY_PATH" ); |
| 2987 | if (LibPath) { |
| 2988 | SmallVector<StringRef, 8> Frags; |
| 2989 | const char EnvPathSeparatorStr[] = {llvm::sys::EnvPathSeparator, '\0'}; |
| 2990 | llvm::SplitString(Source: *LibPath, OutFragments&: Frags, Delimiters: EnvPathSeparatorStr); |
| 2991 | for (StringRef Path : Frags) |
| 2992 | LibraryPaths.emplace_back(Args: Path.trim()); |
| 2993 | } |
| 2994 | |
| 2995 | // Check all of the standard library search paths used by the compiler. |
| 2996 | for (const auto &LibPath : HostTC.getFilePaths()) |
| 2997 | LibraryPaths.emplace_back(Args: LibPath); |
| 2998 | |
| 2999 | // Check the target specific library path for the triple as well. |
| 3000 | SmallString<128> P(D.Dir); |
| 3001 | llvm::sys::path::append(path&: P, a: ".." , b: "lib" , c: Triple.getTriple()); |
| 3002 | LibraryPaths.emplace_back(Args&: P); |
| 3003 | |
| 3004 | OptSpecifier LibomptargetBCPathOpt = |
| 3005 | Triple.isAMDGCN() ? options::OPT_libomptarget_amdgpu_bc_path_EQ |
| 3006 | : Triple.isNVPTX() ? options::OPT_libomptarget_nvptx_bc_path_EQ |
| 3007 | : options::OPT_libomptarget_spirv_bc_path_EQ; |
| 3008 | |
| 3009 | StringRef ArchPrefix = Triple.isAMDGCN() ? "amdgpu" |
| 3010 | : Triple.isNVPTX() ? "nvptx" |
| 3011 | : "spirv" ; |
| 3012 | std::string LibOmpTargetName = ("libomptarget-" + ArchPrefix + ".bc" ).str(); |
| 3013 | |
| 3014 | // First check whether user specifies bc library |
| 3015 | if (const Arg *A = DriverArgs.getLastArg(Ids: LibomptargetBCPathOpt)) { |
| 3016 | SmallString<128> LibOmpTargetFile(A->getValue()); |
| 3017 | if (llvm::sys::fs::exists(Path: LibOmpTargetFile) && |
| 3018 | llvm::sys::fs::is_directory(Path: LibOmpTargetFile)) { |
| 3019 | llvm::sys::path::append(path&: LibOmpTargetFile, a: LibOmpTargetName); |
| 3020 | } |
| 3021 | |
| 3022 | if (llvm::sys::fs::exists(Path: LibOmpTargetFile)) { |
| 3023 | CC1Args.push_back(Elt: "-mlink-builtin-bitcode" ); |
| 3024 | CC1Args.push_back(Elt: DriverArgs.MakeArgString(Str: LibOmpTargetFile)); |
| 3025 | } else { |
| 3026 | D.Diag(DiagID: diag::err_drv_omp_offload_target_bcruntime_not_found) |
| 3027 | << LibOmpTargetFile; |
| 3028 | } |
| 3029 | } else { |
| 3030 | bool FoundBCLibrary = false; |
| 3031 | |
| 3032 | for (StringRef LibraryPath : LibraryPaths) { |
| 3033 | SmallString<128> LibOmpTargetFile(LibraryPath); |
| 3034 | llvm::sys::path::append(path&: LibOmpTargetFile, a: LibOmpTargetName); |
| 3035 | if (llvm::sys::fs::exists(Path: LibOmpTargetFile)) { |
| 3036 | CC1Args.push_back(Elt: "-mlink-builtin-bitcode" ); |
| 3037 | CC1Args.push_back(Elt: DriverArgs.MakeArgString(Str: LibOmpTargetFile)); |
| 3038 | FoundBCLibrary = true; |
| 3039 | break; |
| 3040 | } |
| 3041 | } |
| 3042 | |
| 3043 | if (!FoundBCLibrary) |
| 3044 | D.Diag(DiagID: diag::err_drv_omp_offload_target_missingbcruntime) |
| 3045 | << LibOmpTargetName << ArchPrefix; |
| 3046 | } |
| 3047 | } |
| 3048 | |
| 3049 | void tools::addOpenCLBuiltinsLib(const Driver &D, |
| 3050 | const llvm::opt::ArgList &DriverArgs, |
| 3051 | llvm::opt::ArgStringList &CC1Args) { |
| 3052 | const Arg *A = DriverArgs.getLastArg(Ids: options::OPT_libclc_lib_EQ); |
| 3053 | if (!A) |
| 3054 | return; |
| 3055 | |
| 3056 | // If the namespec is of the form :filename we use it exactly. |
| 3057 | StringRef LibclcNamespec(A->getValue()); |
| 3058 | bool FilenameSearch = LibclcNamespec.consume_front(Prefix: ":" ); |
| 3059 | if (FilenameSearch) { |
| 3060 | SmallString<128> LibclcFile(LibclcNamespec); |
| 3061 | if (llvm::sys::fs::exists(Path: LibclcFile)) { |
| 3062 | CC1Args.push_back(Elt: "-mlink-builtin-bitcode" ); |
| 3063 | CC1Args.push_back(Elt: DriverArgs.MakeArgString(Str: LibclcFile)); |
| 3064 | return; |
| 3065 | } |
| 3066 | D.Diag(DiagID: diag::err_drv_libclc_not_found) << LibclcFile; |
| 3067 | return; |
| 3068 | } |
| 3069 | |
| 3070 | // The OpenCL libraries are stored in <ResourceDir>/lib/<triple>. |
| 3071 | SmallString<128> BasePath(D.ResourceDir); |
| 3072 | llvm::sys::path::append(path&: BasePath, a: "lib" ); |
| 3073 | llvm::sys::path::append(path&: BasePath, a: D.getTargetTriple()); |
| 3074 | |
| 3075 | // First check for a CPU-specific library in <ResourceDir>/lib/<triple>/<CPU>. |
| 3076 | // TODO: Factor this into common logic that checks for valid subtargets. |
| 3077 | if (const Arg *CPUArg = |
| 3078 | DriverArgs.getLastArg(Ids: options::OPT_mcpu_EQ, Ids: options::OPT_march_EQ)) { |
| 3079 | StringRef CPU = CPUArg->getValue(); |
| 3080 | if (!CPU.empty()) { |
| 3081 | SmallString<128> CPUPath(BasePath); |
| 3082 | llvm::sys::path::append(path&: CPUPath, a: CPU, b: "libclc.bc" ); |
| 3083 | if (llvm::sys::fs::exists(Path: CPUPath)) { |
| 3084 | CC1Args.push_back(Elt: "-mlink-builtin-bitcode" ); |
| 3085 | CC1Args.push_back(Elt: DriverArgs.MakeArgString(Str: CPUPath)); |
| 3086 | return; |
| 3087 | } |
| 3088 | } |
| 3089 | } |
| 3090 | |
| 3091 | // Fall back to the generic library for the triple. |
| 3092 | SmallString<128> GenericPath(BasePath); |
| 3093 | llvm::sys::path::append(path&: GenericPath, a: "libclc.bc" ); |
| 3094 | if (llvm::sys::fs::exists(Path: GenericPath)) { |
| 3095 | CC1Args.push_back(Elt: "-mlink-builtin-bitcode" ); |
| 3096 | CC1Args.push_back(Elt: DriverArgs.MakeArgString(Str: GenericPath)); |
| 3097 | return; |
| 3098 | } |
| 3099 | |
| 3100 | D.Diag(DiagID: diag::err_drv_libclc_not_found) << "libclc.bc" ; |
| 3101 | } |
| 3102 | |
| 3103 | void tools::addOutlineAtomicsArgs(const Driver &D, const ToolChain &TC, |
| 3104 | const llvm::opt::ArgList &Args, |
| 3105 | llvm::opt::ArgStringList &CmdArgs, |
| 3106 | const llvm::Triple &Triple) { |
| 3107 | if (Arg *A = Args.getLastArg(Ids: options::OPT_moutline_atomics, |
| 3108 | Ids: options::OPT_mno_outline_atomics)) { |
| 3109 | // Option -moutline-atomics supported for AArch64 target only. |
| 3110 | if (!Triple.isAArch64()) { |
| 3111 | D.Diag(DiagID: diag::warn_drv_moutline_atomics_unsupported_opt) |
| 3112 | << Triple.getArchName() << A->getOption().getName(); |
| 3113 | } else { |
| 3114 | if (A->getOption().matches(ID: options::OPT_moutline_atomics)) { |
| 3115 | CmdArgs.push_back(Elt: "-target-feature" ); |
| 3116 | CmdArgs.push_back(Elt: "+outline-atomics" ); |
| 3117 | } else { |
| 3118 | CmdArgs.push_back(Elt: "-target-feature" ); |
| 3119 | CmdArgs.push_back(Elt: "-outline-atomics" ); |
| 3120 | } |
| 3121 | } |
| 3122 | } else if (Triple.isAArch64() && TC.IsAArch64OutlineAtomicsDefault(Args)) { |
| 3123 | CmdArgs.push_back(Elt: "-target-feature" ); |
| 3124 | CmdArgs.push_back(Elt: "+outline-atomics" ); |
| 3125 | } |
| 3126 | } |
| 3127 | |
| 3128 | void tools::addOffloadCompressArgs(const llvm::opt::ArgList &TCArgs, |
| 3129 | llvm::opt::ArgStringList &CmdArgs) { |
| 3130 | if (TCArgs.hasFlag(Pos: options::OPT_offload_compress, |
| 3131 | Neg: options::OPT_no_offload_compress, Default: false)) |
| 3132 | CmdArgs.push_back(Elt: "--compress" ); |
| 3133 | if (TCArgs.hasArg(Ids: options::OPT_v)) |
| 3134 | CmdArgs.push_back(Elt: "--verbose" ); |
| 3135 | if (auto *Arg = TCArgs.getLastArg(Ids: options::OPT_offload_compression_level_EQ)) |
| 3136 | CmdArgs.push_back( |
| 3137 | Elt: TCArgs.MakeArgString(Str: Twine("--compression-level=" ) + Arg->getValue())); |
| 3138 | } |
| 3139 | |
| 3140 | void tools::addMCModel(const Driver &D, const llvm::opt::ArgList &Args, |
| 3141 | const llvm::Triple &Triple, |
| 3142 | const llvm::Reloc::Model &RelocationModel, |
| 3143 | llvm::opt::ArgStringList &CmdArgs) { |
| 3144 | if (Arg *A = Args.getLastArg(Ids: options::OPT_mcmodel_EQ)) { |
| 3145 | StringRef CM = A->getValue(); |
| 3146 | bool Ok = false; |
| 3147 | if (Triple.isOSAIX() && CM == "medium" ) |
| 3148 | CM = "large" ; |
| 3149 | if (Triple.isAArch64(PointerWidth: 64)) { |
| 3150 | Ok = CM == "tiny" || CM == "small" || CM == "large" ; |
| 3151 | if (CM == "large" && !Triple.isOSBinFormatMachO() && |
| 3152 | RelocationModel != llvm::Reloc::Static) |
| 3153 | D.Diag(DiagID: diag::err_drv_argument_only_allowed_with) |
| 3154 | << A->getAsString(Args) << "-fno-pic" ; |
| 3155 | } else if (Triple.isLoongArch()) { |
| 3156 | if (CM == "extreme" && |
| 3157 | Args.hasFlagNoClaim(Pos: options::OPT_fplt, Neg: options::OPT_fno_plt, Default: false)) |
| 3158 | D.Diag(DiagID: diag::err_drv_argument_not_allowed_with) |
| 3159 | << A->getAsString(Args) << "-fplt" ; |
| 3160 | Ok = CM == "normal" || CM == "medium" || CM == "extreme" ; |
| 3161 | // Convert to LLVM recognizable names. |
| 3162 | if (Ok) |
| 3163 | CM = llvm::StringSwitch<StringRef>(CM) |
| 3164 | .Case(S: "normal" , Value: "small" ) |
| 3165 | .Case(S: "extreme" , Value: "large" ) |
| 3166 | .Default(Value: CM); |
| 3167 | } else if (Triple.isPPC64() || Triple.isOSAIX()) { |
| 3168 | Ok = CM == "small" || CM == "medium" || CM == "large" ; |
| 3169 | } else if (Triple.isRISCV()) { |
| 3170 | // Large code model is disallowed to be used with PIC code model. |
| 3171 | if (CM == "large" && RelocationModel != llvm::Reloc::Static) |
| 3172 | D.Diag(DiagID: diag::err_drv_argument_not_allowed_with) |
| 3173 | << A->getAsString(Args) << "-fpic" ; |
| 3174 | if (CM == "medlow" ) |
| 3175 | CM = "small" ; |
| 3176 | else if (CM == "medany" ) |
| 3177 | CM = "medium" ; |
| 3178 | Ok = CM == "small" || CM == "medium" || |
| 3179 | (CM == "large" && Triple.isRISCV64()); |
| 3180 | } else if (Triple.getArch() == llvm::Triple::x86_64) { |
| 3181 | Ok = llvm::is_contained(Set: {"small" , "kernel" , "medium" , "large" }, Element: CM); |
| 3182 | } else if (Triple.isNVPTX() || Triple.isAMDGPU() || Triple.isSPIRV()) { |
| 3183 | // NVPTX/AMDGPU/SPIRV does not care about the code model and will accept |
| 3184 | // whatever works for the host. |
| 3185 | Ok = true; |
| 3186 | } else if (Triple.isSPARC64()) { |
| 3187 | if (CM == "medlow" ) |
| 3188 | CM = "small" ; |
| 3189 | else if (CM == "medmid" ) |
| 3190 | CM = "medium" ; |
| 3191 | else if (CM == "medany" ) |
| 3192 | CM = "large" ; |
| 3193 | Ok = CM == "small" || CM == "medium" || CM == "large" ; |
| 3194 | } else if (Triple.getArch() == llvm::Triple::lanai) { |
| 3195 | Ok = llvm::is_contained(Set: {"small" , "medium" , "large" }, Element: CM); |
| 3196 | } |
| 3197 | if (Ok) { |
| 3198 | CmdArgs.push_back(Elt: Args.MakeArgString(Str: "-mcmodel=" + CM)); |
| 3199 | } else { |
| 3200 | D.Diag(DiagID: diag::err_drv_unsupported_option_argument_for_target) |
| 3201 | << A->getSpelling() << CM << Triple.getTriple(); |
| 3202 | } |
| 3203 | } |
| 3204 | |
| 3205 | if (Triple.getArch() == llvm::Triple::x86_64) { |
| 3206 | bool IsMediumCM = false; |
| 3207 | bool IsLargeCM = false; |
| 3208 | if (Arg *A = Args.getLastArg(Ids: options::OPT_mcmodel_EQ)) { |
| 3209 | IsMediumCM = StringRef(A->getValue()) == "medium" ; |
| 3210 | IsLargeCM = StringRef(A->getValue()) == "large" ; |
| 3211 | } |
| 3212 | if (Arg *A = Args.getLastArg(Ids: options::OPT_mlarge_data_threshold_EQ)) { |
| 3213 | if (!IsMediumCM && !IsLargeCM) { |
| 3214 | D.Diag(DiagID: diag::warn_drv_large_data_threshold_invalid_code_model) |
| 3215 | << A->getOption().getRenderName(); |
| 3216 | } else { |
| 3217 | A->render(Args, Output&: CmdArgs); |
| 3218 | } |
| 3219 | } else if (IsMediumCM) { |
| 3220 | CmdArgs.push_back(Elt: "-mlarge-data-threshold=65536" ); |
| 3221 | } else if (IsLargeCM) { |
| 3222 | CmdArgs.push_back(Elt: "-mlarge-data-threshold=0" ); |
| 3223 | } |
| 3224 | } |
| 3225 | } |
| 3226 | |
| 3227 | void tools::handleColorDiagnosticsArgs(const Driver &D, const ArgList &Args, |
| 3228 | ArgStringList &CmdArgs) { |
| 3229 | // Color diagnostics are parsed by the driver directly from argv and later |
| 3230 | // re-parsed to construct this job; claim any possible color diagnostic here |
| 3231 | // to avoid warn_drv_unused_argument and diagnose bad |
| 3232 | // OPT_fdiagnostics_color_EQ values. |
| 3233 | Args.getLastArg(Ids: options::OPT_fcolor_diagnostics, |
| 3234 | Ids: options::OPT_fno_color_diagnostics); |
| 3235 | if (const Arg *A = Args.getLastArg(Ids: options::OPT_fdiagnostics_color_EQ)) { |
| 3236 | StringRef Value(A->getValue()); |
| 3237 | if (Value != "always" && Value != "never" && Value != "auto" ) |
| 3238 | D.Diag(DiagID: diag::err_drv_invalid_argument_to_option) |
| 3239 | << Value << A->getOption().getName(); |
| 3240 | } |
| 3241 | |
| 3242 | if (D.getDiags().getDiagnosticOptions().ShowColors) |
| 3243 | CmdArgs.push_back(Elt: "-fcolor-diagnostics" ); |
| 3244 | } |
| 3245 | |
| 3246 | void tools::escapeSpacesAndBackslashes(const char *Arg, |
| 3247 | llvm::SmallVectorImpl<char> &Res) { |
| 3248 | for (; *Arg; ++Arg) { |
| 3249 | switch (*Arg) { |
| 3250 | default: |
| 3251 | break; |
| 3252 | case ' ': |
| 3253 | case '\\': |
| 3254 | Res.push_back(Elt: '\\'); |
| 3255 | break; |
| 3256 | } |
| 3257 | Res.push_back(Elt: *Arg); |
| 3258 | } |
| 3259 | } |
| 3260 | |
| 3261 | const char *tools::renderEscapedCommandLine(const ToolChain &TC, |
| 3262 | const llvm::opt::ArgList &Args) { |
| 3263 | const Driver &D = TC.getDriver(); |
| 3264 | const char *Exec = D.getClangProgramPath(); |
| 3265 | |
| 3266 | llvm::opt::ArgStringList OriginalArgs; |
| 3267 | for (const auto &Arg : Args) |
| 3268 | Arg->render(Args, Output&: OriginalArgs); |
| 3269 | |
| 3270 | llvm::SmallString<256> Flags; |
| 3271 | escapeSpacesAndBackslashes(Arg: Exec, Res&: Flags); |
| 3272 | for (const char *OriginalArg : OriginalArgs) { |
| 3273 | llvm::SmallString<128> EscapedArg; |
| 3274 | escapeSpacesAndBackslashes(Arg: OriginalArg, Res&: EscapedArg); |
| 3275 | Flags += " " ; |
| 3276 | Flags += EscapedArg; |
| 3277 | } |
| 3278 | |
| 3279 | return Args.MakeArgString(Str: Flags); |
| 3280 | } |
| 3281 | |
| 3282 | bool tools::shouldRecordCommandLine(const ToolChain &TC, |
| 3283 | const llvm::opt::ArgList &Args, |
| 3284 | bool &FRecordCommandLine, |
| 3285 | bool &GRecordCommandLine) { |
| 3286 | const Driver &D = TC.getDriver(); |
| 3287 | const llvm::Triple &Triple = TC.getEffectiveTriple(); |
| 3288 | const std::string &TripleStr = Triple.getTriple(); |
| 3289 | |
| 3290 | FRecordCommandLine = |
| 3291 | Args.hasFlag(Pos: options::OPT_frecord_command_line, |
| 3292 | Neg: options::OPT_fno_record_command_line, Default: false); |
| 3293 | GRecordCommandLine = |
| 3294 | Args.hasFlag(Pos: options::OPT_grecord_command_line, |
| 3295 | Neg: options::OPT_gno_record_command_line, Default: false); |
| 3296 | if (FRecordCommandLine && !Triple.isOSBinFormatELF() && |
| 3297 | !Triple.isOSBinFormatXCOFF() && !Triple.isOSBinFormatMachO()) |
| 3298 | D.Diag(DiagID: diag::err_drv_unsupported_opt_for_target) |
| 3299 | << Args.getLastArg(Ids: options::OPT_frecord_command_line)->getAsString(Args) |
| 3300 | << TripleStr; |
| 3301 | |
| 3302 | return FRecordCommandLine || TC.UseDwarfDebugFlags() || GRecordCommandLine; |
| 3303 | } |
| 3304 | |
| 3305 | void tools::renderGlobalISelOptions(const Driver &D, const ArgList &Args, |
| 3306 | ArgStringList &CmdArgs, |
| 3307 | const llvm::Triple &Triple) { |
| 3308 | if (Arg *A = Args.getLastArg(Ids: options::OPT_fglobal_isel, |
| 3309 | Ids: options::OPT_fno_global_isel)) { |
| 3310 | CmdArgs.push_back(Elt: "-mllvm" ); |
| 3311 | if (A->getOption().matches(ID: options::OPT_fglobal_isel)) { |
| 3312 | CmdArgs.push_back(Elt: "-global-isel=1" ); |
| 3313 | |
| 3314 | // GISel is on by default on AArch64 -O0, so don't bother adding |
| 3315 | // the fallback remarks for it. Other combinations will add a warning of |
| 3316 | // some kind. |
| 3317 | bool IsArchSupported = Triple.getArch() == llvm::Triple::aarch64; |
| 3318 | bool IsOptLevelSupported = false; |
| 3319 | |
| 3320 | Arg *A = Args.getLastArg(Ids: options::OPT_O_Group); |
| 3321 | if (IsArchSupported) { |
| 3322 | if (!A || A->getOption().matches(ID: options::OPT_O0)) |
| 3323 | IsOptLevelSupported = true; |
| 3324 | } |
| 3325 | if (!IsArchSupported || !IsOptLevelSupported) { |
| 3326 | CmdArgs.push_back(Elt: "-mllvm" ); |
| 3327 | CmdArgs.push_back(Elt: "-global-isel-abort=2" ); |
| 3328 | |
| 3329 | if (!IsArchSupported) |
| 3330 | D.Diag(DiagID: diag::warn_drv_global_isel_incomplete) << Triple.getArchName(); |
| 3331 | else |
| 3332 | D.Diag(DiagID: diag::warn_drv_global_isel_incomplete_opt); |
| 3333 | } |
| 3334 | } else { |
| 3335 | CmdArgs.push_back(Elt: "-global-isel=0" ); |
| 3336 | } |
| 3337 | } |
| 3338 | } |
| 3339 | |
| 3340 | void tools::renderCommonIntegerOverflowOptions(const ArgList &Args, |
| 3341 | ArgStringList &CmdArgs) { |
| 3342 | bool use_fwrapv = false; |
| 3343 | bool use_fwrapv_pointer = false; |
| 3344 | for (const Arg *A : Args.filtered( |
| 3345 | Ids: options::OPT_fstrict_overflow, Ids: options::OPT_fno_strict_overflow, |
| 3346 | Ids: options::OPT_fwrapv, Ids: options::OPT_fno_wrapv, |
| 3347 | Ids: options::OPT_fwrapv_pointer, Ids: options::OPT_fno_wrapv_pointer)) { |
| 3348 | A->claim(); |
| 3349 | switch (A->getOption().getID()) { |
| 3350 | case options::OPT_fstrict_overflow: |
| 3351 | use_fwrapv = false; |
| 3352 | use_fwrapv_pointer = false; |
| 3353 | break; |
| 3354 | case options::OPT_fno_strict_overflow: |
| 3355 | use_fwrapv = true; |
| 3356 | use_fwrapv_pointer = true; |
| 3357 | break; |
| 3358 | case options::OPT_fwrapv: |
| 3359 | use_fwrapv = true; |
| 3360 | break; |
| 3361 | case options::OPT_fno_wrapv: |
| 3362 | use_fwrapv = false; |
| 3363 | break; |
| 3364 | case options::OPT_fwrapv_pointer: |
| 3365 | use_fwrapv_pointer = true; |
| 3366 | break; |
| 3367 | case options::OPT_fno_wrapv_pointer: |
| 3368 | use_fwrapv_pointer = false; |
| 3369 | break; |
| 3370 | } |
| 3371 | } |
| 3372 | |
| 3373 | if (use_fwrapv) |
| 3374 | CmdArgs.push_back(Elt: "-fwrapv" ); |
| 3375 | if (use_fwrapv_pointer) |
| 3376 | CmdArgs.push_back(Elt: "-fwrapv-pointer" ); |
| 3377 | } |
| 3378 | |
| 3379 | /// Vectorize at all optimization levels greater than 1 except for -Oz. |
| 3380 | /// For -Oz the loop vectorizer is disabled, while the slp vectorizer is |
| 3381 | /// enabled. |
| 3382 | bool tools::shouldEnableVectorizerAtOLevel(const ArgList &Args, bool isSlpVec) { |
| 3383 | if (Arg *A = Args.getLastArg(Ids: options::OPT_O_Group)) { |
| 3384 | if (A->getOption().matches(ID: options::OPT_O4) || |
| 3385 | A->getOption().matches(ID: options::OPT_Ofast)) |
| 3386 | return true; |
| 3387 | |
| 3388 | if (A->getOption().matches(ID: options::OPT_O0)) |
| 3389 | return false; |
| 3390 | |
| 3391 | assert(A->getOption().matches(options::OPT_O) && "Must have a -O flag" ); |
| 3392 | |
| 3393 | // Vectorize -Os. |
| 3394 | StringRef S(A->getValue()); |
| 3395 | if (S == "s" ) |
| 3396 | return true; |
| 3397 | |
| 3398 | // Don't vectorize -Oz, unless it's the slp vectorizer. |
| 3399 | if (S == "z" ) |
| 3400 | return isSlpVec; |
| 3401 | |
| 3402 | unsigned OptLevel = 0; |
| 3403 | if (S.getAsInteger(Radix: 10, Result&: OptLevel)) |
| 3404 | return false; |
| 3405 | |
| 3406 | return OptLevel > 1; |
| 3407 | } |
| 3408 | |
| 3409 | return false; |
| 3410 | } |
| 3411 | |
| 3412 | void tools::handleVectorizeLoopsArgs(const ArgList &Args, |
| 3413 | ArgStringList &CmdArgs) { |
| 3414 | bool EnableVec = shouldEnableVectorizerAtOLevel(Args, isSlpVec: false); |
| 3415 | if (Args.hasFlag(Pos: options::OPT_fvectorize, Neg: options::OPT_fno_vectorize, |
| 3416 | Default: EnableVec)) |
| 3417 | CmdArgs.push_back(Elt: "-vectorize-loops" ); |
| 3418 | } |
| 3419 | |
| 3420 | void tools::handleVectorizeSLPArgs(const ArgList &Args, |
| 3421 | ArgStringList &CmdArgs) { |
| 3422 | bool EnableSLPVec = shouldEnableVectorizerAtOLevel(Args, isSlpVec: true); |
| 3423 | if (Args.hasFlag(Pos: options::OPT_fslp_vectorize, Neg: options::OPT_fno_slp_vectorize, |
| 3424 | Default: EnableSLPVec)) |
| 3425 | CmdArgs.push_back(Elt: "-vectorize-slp" ); |
| 3426 | } |
| 3427 | |
| 3428 | void tools::handleInterchangeLoopsArgs(const ArgList &Args, |
| 3429 | ArgStringList &CmdArgs) { |
| 3430 | if (Args.hasFlag(Pos: options::OPT_floop_interchange, |
| 3431 | Neg: options::OPT_fno_loop_interchange, Default: false)) |
| 3432 | CmdArgs.push_back(Elt: "-floop-interchange" ); |
| 3433 | } |
| 3434 | |
| 3435 | std::string tools::complexRangeKindToStr(LangOptions::ComplexRangeKind Range) { |
| 3436 | switch (Range) { |
| 3437 | case LangOptions::ComplexRangeKind::CX_Full: |
| 3438 | return "full" ; |
| 3439 | break; |
| 3440 | case LangOptions::ComplexRangeKind::CX_Basic: |
| 3441 | return "basic" ; |
| 3442 | break; |
| 3443 | case LangOptions::ComplexRangeKind::CX_Improved: |
| 3444 | return "improved" ; |
| 3445 | break; |
| 3446 | case LangOptions::ComplexRangeKind::CX_Promoted: |
| 3447 | return "promoted" ; |
| 3448 | break; |
| 3449 | case LangOptions::ComplexRangeKind::CX_None: |
| 3450 | return "none" ; |
| 3451 | break; |
| 3452 | } |
| 3453 | llvm_unreachable("Fully covered switch above" ); |
| 3454 | } |
| 3455 | |
| 3456 | std::string |
| 3457 | tools::renderComplexRangeOption(LangOptionsBase::ComplexRangeKind Range) { |
| 3458 | std::string ComplexRangeStr = complexRangeKindToStr(Range); |
| 3459 | if (!ComplexRangeStr.empty()) |
| 3460 | return "-complex-range=" + ComplexRangeStr; |
| 3461 | return ComplexRangeStr; |
| 3462 | } |
| 3463 | |
| 3464 | static void emitComplexRangeDiag(const Driver &D, StringRef LastOpt, |
| 3465 | LangOptions::ComplexRangeKind Range, |
| 3466 | StringRef NewOpt, |
| 3467 | LangOptions::ComplexRangeKind NewRange) { |
| 3468 | // Do not emit a warning if NewOpt overrides LastOpt in the following cases. |
| 3469 | // |
| 3470 | // | LastOpt | NewOpt | |
| 3471 | // |-----------------------|-----------------------| |
| 3472 | // | -fcx-limited-range | -fno-cx-limited-range | |
| 3473 | // | -fno-cx-limited-range | -fcx-limited-range | |
| 3474 | // | -fcx-fortran-rules | -fno-cx-fortran-rules | |
| 3475 | // | -fno-cx-fortran-rules | -fcx-fortran-rules | |
| 3476 | // | -ffast-math | -fno-fast-math | |
| 3477 | // | -ffp-model= | -ffast-math | |
| 3478 | // | -ffp-model= | -fno-fast-math | |
| 3479 | // | -ffp-model= | -ffp-model= | |
| 3480 | // | -fcomplex-arithmetic= | -fcomplex-arithmetic= | |
| 3481 | if (LastOpt == NewOpt || NewOpt.empty() || LastOpt.empty() || |
| 3482 | (LastOpt == "-fcx-limited-range" && NewOpt == "-fno-cx-limited-range" ) || |
| 3483 | (LastOpt == "-fno-cx-limited-range" && NewOpt == "-fcx-limited-range" ) || |
| 3484 | (LastOpt == "-fcx-fortran-rules" && NewOpt == "-fno-cx-fortran-rules" ) || |
| 3485 | (LastOpt == "-fno-cx-fortran-rules" && NewOpt == "-fcx-fortran-rules" ) || |
| 3486 | (LastOpt == "-ffast-math" && NewOpt == "-fno-fast-math" ) || |
| 3487 | (LastOpt.starts_with(Prefix: "-ffp-model=" ) && NewOpt == "-ffast-math" ) || |
| 3488 | (LastOpt.starts_with(Prefix: "-ffp-model=" ) && NewOpt == "-fno-fast-math" ) || |
| 3489 | (LastOpt.starts_with(Prefix: "-ffp-model=" ) && |
| 3490 | NewOpt.starts_with(Prefix: "-ffp-model=" )) || |
| 3491 | (LastOpt.starts_with(Prefix: "-fcomplex-arithmetic=" ) && |
| 3492 | NewOpt.starts_with(Prefix: "-fcomplex-arithmetic=" ))) |
| 3493 | return; |
| 3494 | |
| 3495 | D.Diag(DiagID: clang::diag::warn_drv_overriding_complex_range) |
| 3496 | << LastOpt << NewOpt << complexRangeKindToStr(Range) |
| 3497 | << complexRangeKindToStr(Range: NewRange); |
| 3498 | } |
| 3499 | |
| 3500 | void tools::setComplexRange(const Driver &D, StringRef NewOpt, |
| 3501 | LangOptions::ComplexRangeKind NewRange, |
| 3502 | StringRef &LastOpt, |
| 3503 | LangOptions::ComplexRangeKind &Range) { |
| 3504 | // Warn if user overrides the previously set complex number |
| 3505 | // multiplication/division option. |
| 3506 | if (Range != LangOptions::ComplexRangeKind::CX_None && Range != NewRange) |
| 3507 | emitComplexRangeDiag(D, LastOpt, Range, NewOpt, NewRange); |
| 3508 | LastOpt = NewOpt; |
| 3509 | Range = NewRange; |
| 3510 | } |
| 3511 | |
| 3512 | void tools::constructLLVMLinkCommand(Compilation &C, const Tool &T, |
| 3513 | const JobAction &JA, |
| 3514 | const InputInfoList &JobInputs, |
| 3515 | const ArgStringList &LinkerInputs, |
| 3516 | const InputInfo &Output, |
| 3517 | const llvm::opt::ArgList &Args, |
| 3518 | const char *OutputFilename) { |
| 3519 | // Construct llvm-link command. |
| 3520 | // The output from llvm-link is a bitcode file. |
| 3521 | |
| 3522 | assert(!LinkerInputs.empty() && !JobInputs.empty() && |
| 3523 | "Must have at least one input." ); |
| 3524 | |
| 3525 | ArgStringList LlvmLinkArgs( |
| 3526 | {"-o" , OutputFilename ? OutputFilename : Output.getFilename()}); |
| 3527 | |
| 3528 | LlvmLinkArgs.append(RHS: LinkerInputs); |
| 3529 | |
| 3530 | const ToolChain &TC = T.getToolChain(); |
| 3531 | const char *LlvmLink = Args.MakeArgString(Str: TC.GetProgramPath(Name: "llvm-link" )); |
| 3532 | C.addCommand(C: std::make_unique<Command>(args: JA, args: T, args: ResponseFileSupport::None(), |
| 3533 | args&: LlvmLink, args&: LlvmLinkArgs, args: JobInputs, |
| 3534 | args: Output)); |
| 3535 | } |
| 3536 | |