Index: clang/lib/Driver/Driver.cpp =================================================================== --- clang/lib/Driver/Driver.cpp +++ clang/lib/Driver/Driver.cpp @@ -600,8 +600,9 @@ StringRef LTOName("full"); - const Arg *A = Args.getLastArg(OptEq); - if (A) + const Arg *A = Args.getLastArg(OptEq, OptPos); + // Use the OptEq only if it is after the -flto option. + if (A && A->getOption().matches(OptEq)) LTOName = A->getValue(); LTOMode = llvm::StringSwitch(LTOName) Index: clang/lib/Driver/ToolChains/Clang.cpp =================================================================== --- clang/lib/Driver/ToolChains/Clang.cpp +++ clang/lib/Driver/ToolChains/Clang.cpp @@ -4492,14 +4492,13 @@ if (IsUsingLTO) { if (!IsDeviceOffloadAction) { - if (Args.hasArg(options::OPT_flto)) + Arg *A = Args.getLastArg(options::OPT_flto, options::OPT_flto_EQ); + if (A && A->getOption().matches(options::OPT_flto)) CmdArgs.push_back("-flto"); - else { - if (D.getLTOMode() == LTOK_Thin) - CmdArgs.push_back("-flto=thin"); - else - CmdArgs.push_back("-flto=full"); - } + else if (D.getLTOMode() == LTOK_Thin) + CmdArgs.push_back("-flto=thin"); + else + CmdArgs.push_back("-flto=full"); CmdArgs.push_back("-flto-unit"); } else if (Triple.isAMDGPU()) { // Only AMDGPU supports device-side LTO Index: clang/test/Driver/lto.c =================================================================== --- clang/test/Driver/lto.c +++ clang/test/Driver/lto.c @@ -85,3 +85,15 @@ // FLTO-AUTO: -flto=full // FLTO-JOBSERVER: -flto=full // + +// Pass the last -flto argument +// RUN: %clang -target x86_64-unknown-linux -### %s -flto -flto=thin 2>&1 | \ +// RUN: FileCheck --check-prefix=FLTO-THIN %s +// RUN: %clang -target x86_64-unknown-linux -### %s -flto=thin -flto=full 2>&1 | \ +// RUN: FileCheck --check-prefix=FLTO-FULL %s +// RUN: %clang -target x86_64-unknown-linux -### %s -flto=thin -flto 2>&1 | \ +// RUN: FileCheck --check-prefix=FLTO %s +// +// FLTO-THIN: -flto=thin +// FLTO-FULL: -flto=full +// FLTO: "-flto"