[flang-commits] [clang] [flang] [lldb] [llvm] [mlir] [polly] [IR] Store Triple in Module (NFC) (PR #129868)

Nikita Popov via flang-commits flang-commits at lists.llvm.org
Wed Mar 5 07:45:08 PST 2025


https://github.com/nikic updated https://github.com/llvm/llvm-project/pull/129868

>From 13e2505e361d7ed462486162a5fe56b904018f65 Mon Sep 17 00:00:00 2001
From: Nikita Popov <npopov at redhat.com>
Date: Tue, 4 Mar 2025 17:04:48 +0100
Subject: [PATCH 1/4] [IR] Store Triple in Module (NFC)

The module currently stores the target triple as a string. This
means that any code that wants to actually use the triple first
has to instantiate a Triple, which is somewhat expensive. The
change in #121652 caused a moderate compile-time regression due
to this. While it would be easy enough to work around, I think
that architecturally, it makes more sense to store the parsed
Triple in the module, so that it can always be directly queried.

For this change, I've opted not to add any magic conversions
between std::string and Triple for backwards-compatibilty purses,
and instead write out needed Triple()s or str()s explicitly. This
is because I think a decent number of them should be changed to
work on Triple as well, to avoid unnecessary conversions back and
forth.

The only interesting part in this patch is that the default triple
is Triple("") instead of Triple() to preserve existing behavior.
The former defaults to using the ELF object format instead of
unknown object format. We should fix that as well.
---
 clang/lib/CodeGen/BackendUtil.cpp               |  2 +-
 clang/lib/CodeGen/CodeGenAction.cpp             |  6 +++---
 clang/lib/CodeGen/ModuleBuilder.cpp             |  2 +-
 .../CodeGen/ObjectFilePCHContainerWriter.cpp    |  2 +-
 clang/lib/Interpreter/DeviceOffload.cpp         |  4 ++--
 .../clang-fuzzer/handle-llvm/handle_llvm.cpp    |  4 ++--
 .../clang-linker-wrapper/ClangLinkerWrapper.cpp | 13 +++++++------
 .../LLJITWithThinLTOSummaries.cpp               |  2 +-
 .../llvm/ExecutionEngine/Orc/ExecutionUtils.h   |  2 +-
 .../include/llvm/Frontend/OpenMP/OMPIRBuilder.h |  2 +-
 llvm/include/llvm/IR/Module.h                   | 12 +++++++-----
 llvm/include/llvm/LTO/legacy/LTOModule.h        |  8 ++------
 llvm/include/llvm/TargetParser/Triple.h         |  3 +++
 llvm/lib/Analysis/DXILMetadataAnalysis.cpp      |  2 +-
 llvm/lib/Analysis/Lint.cpp                      |  2 +-
 llvm/lib/Analysis/TargetLibraryInfo.cpp         |  7 +++----
 llvm/lib/AsmParser/LLParser.cpp                 |  4 ++--
 llvm/lib/Bitcode/Reader/BitcodeReader.cpp       |  6 +++---
 llvm/lib/Bitcode/Writer/BitcodeWriter.cpp       |  4 ++--
 llvm/lib/CodeGen/AsmPrinter/CodeViewDebug.cpp   | 10 +++++-----
 llvm/lib/CodeGen/AssignmentTrackingAnalysis.cpp |  3 +--
 llvm/lib/CodeGen/GlobalMerge.cpp                |  2 +-
 llvm/lib/CodeGen/MIRParser/MIRParser.cpp        |  8 ++++----
 llvm/lib/CodeGen/StackProtector.cpp             |  2 +-
 llvm/lib/CodeGen/WinEHPrepare.cpp               |  2 +-
 llvm/lib/ExecutionEngine/TargetSelect.cpp       |  2 +-
 llvm/lib/Frontend/Offloading/OffloadWrapper.cpp |  2 +-
 llvm/lib/Frontend/Offloading/Utility.cpp        |  6 +++---
 llvm/lib/Frontend/OpenMP/OMPIRBuilder.cpp       |  4 ++--
 llvm/lib/IR/AsmWriter.cpp                       |  2 +-
 llvm/lib/IR/Core.cpp                            |  6 +++---
 llvm/lib/IR/EHPersonalities.cpp                 |  2 +-
 llvm/lib/IR/Globals.cpp                         |  6 ++----
 llvm/lib/IR/ValueSymbolTable.cpp                |  2 +-
 llvm/lib/IR/Verifier.cpp                        |  2 +-
 llvm/lib/LTO/LTO.cpp                            |  5 +++--
 llvm/lib/LTO/LTOBackend.cpp                     | 17 +++++++++--------
 llvm/lib/LTO/LTOCodeGenerator.cpp               |  6 +++---
 llvm/lib/LTO/LTOModule.cpp                      |  6 +++---
 llvm/lib/LTO/ThinLTOCodeGenerator.cpp           | 14 +++++++-------
 llvm/lib/LTO/UpdateCompilerUsed.cpp             |  2 +-
 llvm/lib/Linker/IRMover.cpp                     |  8 ++++----
 llvm/lib/Object/IRObjectFile.cpp                |  2 +-
 llvm/lib/Object/IRSymtab.cpp                    |  7 +++----
 llvm/lib/ProfileData/InstrProf.cpp              |  4 ++--
 .../AArch64/AArch64Arm64ECCallLowering.cpp      |  2 +-
 .../AArch64/AArch64MachineFunctionInfo.cpp      |  2 +-
 llvm/lib/Target/AArch64/AArch64StackTagging.cpp |  5 ++---
 llvm/lib/Target/AMDGPU/AMDGPUSwLowerLDS.cpp     |  4 ++--
 llvm/lib/Target/DirectX/DXILOpBuilder.cpp       |  2 +-
 llvm/lib/Target/DirectX/DXILOpLowering.cpp      |  6 +++---
 .../DirectX/DXILWriter/DXILBitcodeWriter.cpp    |  4 ++--
 .../DirectX/DXILWriter/DXILWriterPass.cpp       |  4 ++--
 .../Hexagon/HexagonLoopIdiomRecognition.cpp     |  2 +-
 .../lib/Target/Mips/AsmParser/MipsAsmParser.cpp |  6 +++---
 llvm/lib/Target/SPIRV/SPIRVAPI.cpp              | 10 +++++-----
 llvm/lib/Target/X86/X86MCInstLower.cpp          |  5 ++---
 llvm/lib/Transforms/CFGuard/CFGuard.cpp         |  4 ++--
 llvm/lib/Transforms/Coroutines/CoroSplit.cpp    |  3 +--
 llvm/lib/Transforms/IPO/Internalize.cpp         |  6 +++---
 .../Instrumentation/AddressSanitizer.cpp        |  9 ++++-----
 .../Instrumentation/GCOVProfiling.cpp           |  6 +++---
 .../Instrumentation/HWAddressSanitizer.cpp      |  4 ++--
 .../Instrumentation/InstrOrderFile.cpp          |  2 +-
 .../Instrumentation/InstrProfiling.cpp          |  2 +-
 .../Transforms/Instrumentation/MemProfiler.cpp  | 10 +++++-----
 .../Instrumentation/MemorySanitizer.cpp         |  2 +-
 .../Instrumentation/SanitizerBinaryMetadata.cpp |  2 +-
 .../Instrumentation/SanitizerCoverage.cpp       |  2 +-
 .../Instrumentation/ThreadSanitizer.cpp         |  2 +-
 .../Instrumentation/TypeSanitizer.cpp           |  2 +-
 llvm/tools/bugpoint/BugDriver.cpp               |  3 ++-
 llvm/tools/llc/llc.cpp                          |  4 ++--
 llvm/tools/lli/lli.cpp                          | 11 +++++------
 llvm/tools/llvm-exegesis/lib/Assembler.cpp      |  2 +-
 .../tools/llvm-isel-fuzzer/llvm-isel-fuzzer.cpp |  2 +-
 llvm/tools/llvm-opt-fuzzer/llvm-opt-fuzzer.cpp  |  2 +-
 llvm/tools/lto/lto.cpp                          |  4 ++--
 llvm/tools/opt/optdriver.cpp                    |  2 +-
 llvm/unittests/Analysis/LazyCallGraphTest.cpp   |  2 +-
 .../ExecutionEngine/MCJIT/MCJITTestBase.h       |  2 +-
 .../ExecutionEngine/Orc/OrcTestCommon.cpp       |  8 ++++----
 .../Orc/RTDyldObjectLinkingLayerTest.cpp        |  4 ++--
 .../ExecutionEngine/Orc/ReOptimizeLayerTest.cpp |  2 +-
 llvm/unittests/IR/LegacyPassManagerTest.cpp     |  2 +-
 llvm/unittests/Target/AArch64/InstSizes.cpp     |  2 +-
 llvm/unittests/Target/ARM/InstSizes.cpp         |  2 +-
 llvm/unittests/Target/LoongArch/InstSizes.cpp   |  2 +-
 .../Target/X86/MachineSizeOptsTest.cpp          |  2 +-
 .../Transforms/Vectorize/VPlanHCFGTest.cpp      |  4 ++--
 .../common/src/PluginInterface.cpp              |  2 +-
 polly/lib/CodeGen/IslNodeBuilder.cpp            |  3 +--
 polly/lib/CodeGen/PerfMonitor.cpp               |  2 +-
 93 files changed, 195 insertions(+), 201 deletions(-)

diff --git a/clang/lib/CodeGen/BackendUtil.cpp b/clang/lib/CodeGen/BackendUtil.cpp
index 1750719e17670..62a0e3c69bad1 100644
--- a/clang/lib/CodeGen/BackendUtil.cpp
+++ b/clang/lib/CodeGen/BackendUtil.cpp
@@ -595,7 +595,7 @@ static void setCommandLineOpts(const CodeGenOptions &CodeGenOpts) {
 void EmitAssemblyHelper::CreateTargetMachine(bool MustCreateTM) {
   // Create the TargetMachine for generating code.
   std::string Error;
-  std::string Triple = TheModule->getTargetTriple();
+  std::string Triple = TheModule->getTargetTriple().str();
   const llvm::Target *TheTarget = TargetRegistry::lookupTarget(Triple, Error);
   if (!TheTarget) {
     if (MustCreateTM)
diff --git a/clang/lib/CodeGen/CodeGenAction.cpp b/clang/lib/CodeGen/CodeGenAction.cpp
index 7aa3639cabf39..4321efd49af36 100644
--- a/clang/lib/CodeGen/CodeGenAction.cpp
+++ b/clang/lib/CodeGen/CodeGenAction.cpp
@@ -1032,7 +1032,7 @@ CodeGenAction::loadModule(MemoryBufferRef MBRef) {
     // linker using merged object file.
     if (!Bm) {
       auto M = std::make_unique<llvm::Module>("empty", *VMContext);
-      M->setTargetTriple(CI.getTargetOpts().Triple);
+      M->setTargetTriple(Triple(CI.getTargetOpts().Triple));
       return M;
     }
     Expected<std::unique_ptr<llvm::Module>> MOrErr =
@@ -1123,10 +1123,10 @@ void CodeGenAction::ExecuteAction() {
     return;
 
   const TargetOptions &TargetOpts = CI.getTargetOpts();
-  if (TheModule->getTargetTriple() != TargetOpts.Triple) {
+  if (TheModule->getTargetTriple().str() != TargetOpts.Triple) {
     Diagnostics.Report(SourceLocation(), diag::warn_fe_override_module)
         << TargetOpts.Triple;
-    TheModule->setTargetTriple(TargetOpts.Triple);
+    TheModule->setTargetTriple(Triple(TargetOpts.Triple));
   }
 
   EmbedObject(TheModule.get(), CodeGenOpts, Diagnostics);
diff --git a/clang/lib/CodeGen/ModuleBuilder.cpp b/clang/lib/CodeGen/ModuleBuilder.cpp
index d4e0ab0339a8b..09a7d79ae4afb 100644
--- a/clang/lib/CodeGen/ModuleBuilder.cpp
+++ b/clang/lib/CodeGen/ModuleBuilder.cpp
@@ -151,7 +151,7 @@ namespace {
     void Initialize(ASTContext &Context) override {
       Ctx = &Context;
 
-      M->setTargetTriple(Ctx->getTargetInfo().getTriple().getTriple());
+      M->setTargetTriple(Ctx->getTargetInfo().getTriple());
       M->setDataLayout(Ctx->getTargetInfo().getDataLayoutString());
       const auto &SDKVersion = Ctx->getTargetInfo().getSDKVersion();
       if (!SDKVersion.empty())
diff --git a/clang/lib/CodeGen/ObjectFilePCHContainerWriter.cpp b/clang/lib/CodeGen/ObjectFilePCHContainerWriter.cpp
index 788c8b932ab52..e32778d1b4767 100644
--- a/clang/lib/CodeGen/ObjectFilePCHContainerWriter.cpp
+++ b/clang/lib/CodeGen/ObjectFilePCHContainerWriter.cpp
@@ -255,7 +255,7 @@ class PCHContainerGenerator : public ASTConsumer {
     if (Diags.hasErrorOccurred())
       return;
 
-    M->setTargetTriple(Ctx.getTargetInfo().getTriple().getTriple());
+    M->setTargetTriple(Ctx.getTargetInfo().getTriple());
     M->setDataLayout(Ctx.getTargetInfo().getDataLayoutString());
 
     // PCH files don't have a signature field in the control block,
diff --git a/clang/lib/Interpreter/DeviceOffload.cpp b/clang/lib/Interpreter/DeviceOffload.cpp
index 1999d63d1aa04..8fb484d185704 100644
--- a/clang/lib/Interpreter/DeviceOffload.cpp
+++ b/clang/lib/Interpreter/DeviceOffload.cpp
@@ -77,13 +77,13 @@ llvm::Expected<llvm::StringRef> IncrementalCUDADeviceParser::GeneratePTX() {
   std::string Error;
 
   const llvm::Target *Target = llvm::TargetRegistry::lookupTarget(
-      PTU.TheModule->getTargetTriple(), Error);
+      PTU.TheModule->getTargetTriple().str(), Error);
   if (!Target)
     return llvm::make_error<llvm::StringError>(std::move(Error),
                                                std::error_code());
   llvm::TargetOptions TO = llvm::TargetOptions();
   llvm::TargetMachine *TargetMachine = Target->createTargetMachine(
-      PTU.TheModule->getTargetTriple(), TargetOpts.CPU, "", TO,
+      PTU.TheModule->getTargetTriple().str(), TargetOpts.CPU, "", TO,
       llvm::Reloc::Model::PIC_);
   PTU.TheModule->setDataLayout(TargetMachine->createDataLayout());
 
diff --git a/clang/tools/clang-fuzzer/handle-llvm/handle_llvm.cpp b/clang/tools/clang-fuzzer/handle-llvm/handle_llvm.cpp
index 798b34b3ef0af..4618c0bcc6be8 100644
--- a/clang/tools/clang-fuzzer/handle-llvm/handle_llvm.cpp
+++ b/clang/tools/clang-fuzzer/handle-llvm/handle_llvm.cpp
@@ -127,8 +127,8 @@ static std::string OptLLVM(const std::string &IR, CodeGenOptLevel OLvl) {
     ErrorAndExit(E);
 
   std::unique_ptr<TargetMachine> TM(TheTarget->createTargetMachine(
-      M->getTargetTriple(), codegen::getCPUStr(), codegen::getFeaturesStr(),
-      Options, codegen::getExplicitRelocModel(),
+      M->getTargetTriple().str(), codegen::getCPUStr(),
+      codegen::getFeaturesStr(), Options, codegen::getExplicitRelocModel(),
       codegen::getExplicitCodeModel(), OLvl));
   if (!TM)
     ErrorAndExit("Could not create target machine");
diff --git a/clang/tools/clang-linker-wrapper/ClangLinkerWrapper.cpp b/clang/tools/clang-linker-wrapper/ClangLinkerWrapper.cpp
index 7db8f3e27d704..5f5d103bbcf49 100644
--- a/clang/tools/clang-linker-wrapper/ClangLinkerWrapper.cpp
+++ b/clang/tools/clang-linker-wrapper/ClangLinkerWrapper.cpp
@@ -622,16 +622,17 @@ Expected<StringRef> writeOffloadFile(const OffloadFile &File) {
 Expected<StringRef> compileModule(Module &M, OffloadKind Kind) {
   llvm::TimeTraceScope TimeScope("Compile module");
   std::string Msg;
-  const Target *T = TargetRegistry::lookupTarget(M.getTargetTriple(), Msg);
+  const Target *T =
+      TargetRegistry::lookupTarget(M.getTargetTriple().str(), Msg);
   if (!T)
     return createStringError(Msg);
 
   auto Options =
-      codegen::InitTargetOptionsFromCodeGenFlags(Triple(M.getTargetTriple()));
+      codegen::InitTargetOptionsFromCodeGenFlags(M.getTargetTriple());
   StringRef CPU = "";
   StringRef Features = "";
   std::unique_ptr<TargetMachine> TM(
-      T->createTargetMachine(M.getTargetTriple(), CPU, Features, Options,
+      T->createTargetMachine(M.getTargetTriple().str(), CPU, Features, Options,
                              Reloc::PIC_, M.getCodeModel()));
 
   if (M.getDataLayout().isDefault())
@@ -650,7 +651,7 @@ Expected<StringRef> compileModule(Module &M, OffloadKind Kind) {
   auto OS = std::make_unique<llvm::raw_fd_ostream>(FD, true);
 
   legacy::PassManager CodeGenPasses;
-  TargetLibraryInfoImpl TLII(Triple(M.getTargetTriple()));
+  TargetLibraryInfoImpl TLII(M.getTargetTriple());
   CodeGenPasses.add(new TargetLibraryInfoWrapperPass(TLII));
   if (TM->addPassesToEmitFile(CodeGenPasses, *OS, nullptr,
                               CodeGenFileType::ObjectFile))
@@ -674,8 +675,8 @@ wrapDeviceImages(ArrayRef<std::unique_ptr<MemoryBuffer>> Buffers,
 
   LLVMContext Context;
   Module M("offload.wrapper.module", Context);
-  M.setTargetTriple(
-      Args.getLastArgValue(OPT_host_triple_EQ, sys::getDefaultTargetTriple()));
+  M.setTargetTriple(Triple(
+      Args.getLastArgValue(OPT_host_triple_EQ, sys::getDefaultTargetTriple())));
 
   switch (Kind) {
   case OFK_OpenMP:
diff --git a/llvm/examples/OrcV2Examples/LLJITWithThinLTOSummaries/LLJITWithThinLTOSummaries.cpp b/llvm/examples/OrcV2Examples/LLJITWithThinLTOSummaries/LLJITWithThinLTOSummaries.cpp
index f498a97442c44..78152af052c07 100644
--- a/llvm/examples/OrcV2Examples/LLJITWithThinLTOSummaries/LLJITWithThinLTOSummaries.cpp
+++ b/llvm/examples/OrcV2Examples/LLJITWithThinLTOSummaries/LLJITWithThinLTOSummaries.cpp
@@ -207,7 +207,7 @@ int main(int Argc, char *Argv[]) {
           ExitOnErr(JITTargetMachineBuilder::detectHost()));
     } else {
       Builder.setJITTargetMachineBuilder(
-          JITTargetMachineBuilder(Triple(M.getTargetTriple())));
+          JITTargetMachineBuilder(M.getTargetTriple()));
     }
     if (!M.getDataLayout().getStringRepresentation().empty())
       Builder.setDataLayout(M.getDataLayout());
diff --git a/llvm/include/llvm/ExecutionEngine/Orc/ExecutionUtils.h b/llvm/include/llvm/ExecutionEngine/Orc/ExecutionUtils.h
index 593f7a41337cb..67347e851ca1b 100644
--- a/llvm/include/llvm/ExecutionEngine/Orc/ExecutionUtils.h
+++ b/llvm/include/llvm/ExecutionEngine/Orc/ExecutionUtils.h
@@ -104,7 +104,7 @@ class StaticInitGVIterator {
 
   StaticInitGVIterator(Module &M)
       : I(M.global_values().begin()), E(M.global_values().end()),
-        ObjFmt(Triple(M.getTargetTriple()).getObjectFormat()) {
+        ObjFmt(M.getTargetTriple().getObjectFormat()) {
     if (I != E) {
       if (!isStaticInitGlobal(*I))
         moveToNextStaticInitGlobal();
diff --git a/llvm/include/llvm/Frontend/OpenMP/OMPIRBuilder.h b/llvm/include/llvm/Frontend/OpenMP/OMPIRBuilder.h
index 80b4aa2bd2855..28909cef4748d 100644
--- a/llvm/include/llvm/Frontend/OpenMP/OMPIRBuilder.h
+++ b/llvm/include/llvm/Frontend/OpenMP/OMPIRBuilder.h
@@ -479,7 +479,7 @@ class OpenMPIRBuilder {
   /// not have an effect on \p M (see initialize)
   OpenMPIRBuilder(Module &M)
       : M(M), Builder(M.getContext()), OffloadInfoManager(this),
-        T(Triple(M.getTargetTriple())) {}
+        T(M.getTargetTriple()) {}
   ~OpenMPIRBuilder();
 
   class AtomicInfo : public llvm::AtomicInfo {
diff --git a/llvm/include/llvm/IR/Module.h b/llvm/include/llvm/IR/Module.h
index 12b50fc506516..48dc29c24c582 100644
--- a/llvm/include/llvm/IR/Module.h
+++ b/llvm/include/llvm/IR/Module.h
@@ -31,6 +31,7 @@
 #include "llvm/IR/SymbolTableListTraits.h"
 #include "llvm/Support/CBindingWrapping.h"
 #include "llvm/Support/CodeGen.h"
+#include "llvm/TargetParser/Triple.h"
 #include <cstddef>
 #include <cstdint>
 #include <iterator>
@@ -189,8 +190,10 @@ class LLVM_ABI Module {
   std::string ModuleID;           ///< Human readable identifier for the module
   std::string SourceFileName;     ///< Original source file name for module,
                                   ///< recorded in bitcode.
-  std::string TargetTriple;       ///< Platform target triple Module compiled on
-                                  ///< Format: (arch)(sub)-(vendor)-(sys0-(abi)
+  /// Platform target triple Module compiled on
+  /// Format: (arch)(sub)-(vendor)-(sys0-(abi)
+  // FIXME: Default construction is not the same as empty triple :(
+  Triple TargetTriple = Triple("");
   NamedMDSymTabType NamedMDSymTab;  ///< NamedMDNode names.
   DataLayout DL;                  ///< DataLayout associated with the module
   StringMap<unsigned>
@@ -294,8 +297,7 @@ class LLVM_ABI Module {
   const DataLayout &getDataLayout() const { return DL; }
 
   /// Get the target triple which is a string describing the target host.
-  /// @returns a string containing the target triple.
-  const std::string &getTargetTriple() const { return TargetTriple; }
+  const Triple &getTargetTriple() const { return TargetTriple; }
 
   /// Get the global data context.
   /// @returns LLVMContext - a container for LLVM's global information
@@ -338,7 +340,7 @@ class LLVM_ABI Module {
   void setDataLayout(const DataLayout &Other);
 
   /// Set the target triple.
-  void setTargetTriple(StringRef T) { TargetTriple = std::string(T); }
+  void setTargetTriple(Triple T) { TargetTriple = std::move(T); }
 
   /// Set the module-scope inline assembly blocks.
   /// A trailing newline is added if the input doesn't have one.
diff --git a/llvm/include/llvm/LTO/legacy/LTOModule.h b/llvm/include/llvm/LTO/legacy/LTOModule.h
index e861a56bcbac1..91a38b7c0da80 100644
--- a/llvm/include/llvm/LTO/legacy/LTOModule.h
+++ b/llvm/include/llvm/LTO/legacy/LTOModule.h
@@ -118,14 +118,10 @@ struct LTOModule {
   std::unique_ptr<Module> takeModule() { return std::move(Mod); }
 
   /// Return the Module's target triple.
-  const std::string &getTargetTriple() {
-    return getModule().getTargetTriple();
-  }
+  const Triple &getTargetTriple() { return getModule().getTargetTriple(); }
 
   /// Set the Module's target triple.
-  void setTargetTriple(StringRef Triple) {
-    getModule().setTargetTriple(Triple);
-  }
+  void setTargetTriple(Triple T) { getModule().setTargetTriple(T); }
 
   /// Get the number of symbols
   uint32_t getSymbolCount() {
diff --git a/llvm/include/llvm/TargetParser/Triple.h b/llvm/include/llvm/TargetParser/Triple.h
index 09c0d223d9b4d..390ed7fbab8c0 100644
--- a/llvm/include/llvm/TargetParser/Triple.h
+++ b/llvm/include/llvm/TargetParser/Triple.h
@@ -463,6 +463,9 @@ class Triple {
 
   const std::string &getTriple() const { return Data; }
 
+  /// Whether the triple is empty / default constructed.
+  bool empty() const { return Data.empty(); }
+
   /// Get the architecture (first) component of the triple.
   StringRef getArchName() const;
 
diff --git a/llvm/lib/Analysis/DXILMetadataAnalysis.cpp b/llvm/lib/Analysis/DXILMetadataAnalysis.cpp
index a7f666a3f8b48..87aa14e9c701f 100644
--- a/llvm/lib/Analysis/DXILMetadataAnalysis.cpp
+++ b/llvm/lib/Analysis/DXILMetadataAnalysis.cpp
@@ -24,7 +24,7 @@ using namespace dxil;
 
 static ModuleMetadataInfo collectMetadataInfo(Module &M) {
   ModuleMetadataInfo MMDAI;
-  Triple TT(Triple(M.getTargetTriple()));
+  const Triple &TT = M.getTargetTriple();
   MMDAI.DXILVersion = TT.getDXILVersion();
   MMDAI.ShaderModelVersion = TT.getOSVersion();
   MMDAI.ShaderProfile = TT.getEnvironment();
diff --git a/llvm/lib/Analysis/Lint.cpp b/llvm/lib/Analysis/Lint.cpp
index e9d96a0c2972a..1db0ca372d797 100644
--- a/llvm/lib/Analysis/Lint.cpp
+++ b/llvm/lib/Analysis/Lint.cpp
@@ -139,7 +139,7 @@ class Lint : public InstVisitor<Lint> {
 
   Lint(Module *Mod, const DataLayout *DL, AliasAnalysis *AA,
        AssumptionCache *AC, DominatorTree *DT, TargetLibraryInfo *TLI)
-      : Mod(Mod), TT(Triple::normalize(Mod->getTargetTriple())), DL(DL), AA(AA),
+      : Mod(Mod), TT(Mod->getTargetTriple().normalize()), DL(DL), AA(AA),
         AC(AC), DT(DT), TLI(TLI), MessagesStr(Messages) {}
 
   void WriteValues(ArrayRef<const Value *> Vs) {
diff --git a/llvm/lib/Analysis/TargetLibraryInfo.cpp b/llvm/lib/Analysis/TargetLibraryInfo.cpp
index 8557901192e40..3a8cdf946da37 100644
--- a/llvm/lib/Analysis/TargetLibraryInfo.cpp
+++ b/llvm/lib/Analysis/TargetLibraryInfo.cpp
@@ -118,7 +118,7 @@ static bool hasBcmp(const Triple &TT) {
   return TT.isOSFreeBSD() || TT.isOSSolaris();
 }
 
-static bool isCallingConvCCompatible(CallingConv::ID CC, StringRef TT,
+static bool isCallingConvCCompatible(CallingConv::ID CC, const Triple &TT,
                                      FunctionType *FuncTy) {
   switch (CC) {
   default:
@@ -131,7 +131,7 @@ static bool isCallingConvCCompatible(CallingConv::ID CC, StringRef TT,
 
     // The iOS ABI diverges from the standard in some cases, so for now don't
     // try to simplify those calls.
-    if (Triple(TT).isiOS())
+    if (TT.isiOS())
       return false;
 
     if (!FuncTy->getReturnType()->isPointerTy() &&
@@ -1446,8 +1446,7 @@ TargetLibraryInfoImpl::getVectorMappingInfo(StringRef F, const ElementCount &VF,
 TargetLibraryInfo TargetLibraryAnalysis::run(const Function &F,
                                              FunctionAnalysisManager &) {
   if (!BaselineInfoImpl)
-    BaselineInfoImpl =
-        TargetLibraryInfoImpl(Triple(F.getParent()->getTargetTriple()));
+    BaselineInfoImpl = TargetLibraryInfoImpl(F.getParent()->getTargetTriple());
   return TargetLibraryInfo(*BaselineInfoImpl, &F);
 }
 
diff --git a/llvm/lib/AsmParser/LLParser.cpp b/llvm/lib/AsmParser/LLParser.cpp
index 777bf5f7bb386..c8d792981793d 100644
--- a/llvm/lib/AsmParser/LLParser.cpp
+++ b/llvm/lib/AsmParser/LLParser.cpp
@@ -522,7 +522,7 @@ bool LLParser::parseTargetDefinitions(DataLayoutCallbackTy DataLayoutCallback) {
   // Run the override callback to potentially change the data layout string, and
   // parse the data layout string.
   if (auto LayoutOverride =
-          DataLayoutCallback(M->getTargetTriple(), TentativeDLStr)) {
+          DataLayoutCallback(M->getTargetTriple().str(), TentativeDLStr)) {
     TentativeDLStr = *LayoutOverride;
     DLStrLoc = {};
   }
@@ -646,7 +646,7 @@ bool LLParser::parseTargetDefinition(std::string &TentativeDLStr,
     if (parseToken(lltok::equal, "expected '=' after target triple") ||
         parseStringConstant(Str))
       return true;
-    M->setTargetTriple(Str);
+    M->setTargetTriple(Triple(Str));
     return false;
   case lltok::kw_datalayout:
     Lex.Lex();
diff --git a/llvm/lib/Bitcode/Reader/BitcodeReader.cpp b/llvm/lib/Bitcode/Reader/BitcodeReader.cpp
index d687495c42de6..e4dc7d6ed86b0 100644
--- a/llvm/lib/Bitcode/Reader/BitcodeReader.cpp
+++ b/llvm/lib/Bitcode/Reader/BitcodeReader.cpp
@@ -4530,12 +4530,12 @@ Error BitcodeReader::parseModule(uint64_t ResumeBit,
 
     // Auto-upgrade the layout string
     TentativeDataLayoutStr = llvm::UpgradeDataLayoutString(
-        TentativeDataLayoutStr, TheModule->getTargetTriple());
+        TentativeDataLayoutStr, TheModule->getTargetTriple().str());
 
     // Apply override
     if (Callbacks.DataLayout) {
       if (auto LayoutOverride = (*Callbacks.DataLayout)(
-              TheModule->getTargetTriple(), TentativeDataLayoutStr))
+              TheModule->getTargetTriple().str(), TentativeDataLayoutStr))
         TentativeDataLayoutStr = *LayoutOverride;
     }
 
@@ -4719,7 +4719,7 @@ Error BitcodeReader::parseModule(uint64_t ResumeBit,
       std::string S;
       if (convertToString(Record, 0, S))
         return error("Invalid record");
-      TheModule->setTargetTriple(S);
+      TheModule->setTargetTriple(Triple(S));
       break;
     }
     case bitc::MODULE_CODE_DATALAYOUT: {  // DATALAYOUT: [strchr x N]
diff --git a/llvm/lib/Bitcode/Writer/BitcodeWriter.cpp b/llvm/lib/Bitcode/Writer/BitcodeWriter.cpp
index 440a2c9ace8a3..6e2e45a51069d 100644
--- a/llvm/lib/Bitcode/Writer/BitcodeWriter.cpp
+++ b/llvm/lib/Bitcode/Writer/BitcodeWriter.cpp
@@ -1449,8 +1449,8 @@ serializeSanitizerMetadata(const GlobalValue::SanitizerMetadata &Meta) {
 void ModuleBitcodeWriter::writeModuleInfo() {
   // Emit various pieces of data attached to a module.
   if (!M.getTargetTriple().empty())
-    writeStringRecord(Stream, bitc::MODULE_CODE_TRIPLE, M.getTargetTriple(),
-                      0 /*TODO*/);
+    writeStringRecord(Stream, bitc::MODULE_CODE_TRIPLE,
+                      M.getTargetTriple().str(), 0 /*TODO*/);
   const std::string &DL = M.getDataLayoutStr();
   if (!DL.empty())
     writeStringRecord(Stream, bitc::MODULE_CODE_DATALAYOUT, DL, 0 /*TODO*/);
diff --git a/llvm/lib/CodeGen/AsmPrinter/CodeViewDebug.cpp b/llvm/lib/CodeGen/AsmPrinter/CodeViewDebug.cpp
index bda0e266d01de..5c3b900ca29b6 100644
--- a/llvm/lib/CodeGen/AsmPrinter/CodeViewDebug.cpp
+++ b/llvm/lib/CodeGen/AsmPrinter/CodeViewDebug.cpp
@@ -619,7 +619,7 @@ void CodeViewDebug::beginModule(Module *M) {
     return;
   }
 
-  TheCPU = mapArchToCVCPUType(Triple(M->getTargetTriple()).getArch());
+  TheCPU = mapArchToCVCPUType(M->getTargetTriple().getArch());
 
   // Get the current source language.
   const MDNode *Node = *M->debug_compile_units_begin();
@@ -845,7 +845,7 @@ void CodeViewDebug::emitCompilerInformation() {
     Flags |= static_cast<uint32_t>(CompileSym3Flags::PGO);
   }
   using ArchType = llvm::Triple::ArchType;
-  ArchType Arch = Triple(MMI->getModule()->getTargetTriple()).getArch();
+  ArchType Arch = MMI->getModule()->getTargetTriple().getArch();
   if (Asm->TM.Options.Hotpatch || Arch == ArchType::thumb ||
       Arch == ArchType::aarch64) {
     Flags |= static_cast<uint32_t>(CompileSym3Flags::HotPatch);
@@ -1098,7 +1098,7 @@ void CodeViewDebug::emitDebugInfoForFunction(const Function *GV,
     FuncName = std::string(GlobalValue::dropLLVMManglingEscape(GV->getName()));
 
   // Emit FPO data, but only on 32-bit x86. No other platforms use it.
-  if (Triple(MMI->getModule()->getTargetTriple()).getArch() == Triple::x86)
+  if (MMI->getModule()->getTargetTriple().getArch() == Triple::x86)
     OS.emitCVFPOData(Fn);
 
   // Emit a symbol subsection, required by VS2012+ to find function boundaries.
@@ -1560,7 +1560,7 @@ void CodeViewDebug::beginFunctionImpl(const MachineFunction *MF) {
   }
 
   // Mark branches that may potentially be using jump tables with labels.
-  bool isThumb = Triple(MMI->getModule()->getTargetTriple()).getArch() ==
+  bool isThumb = MMI->getModule()->getTargetTriple().getArch() ==
                  llvm::Triple::ArchType::thumb;
   discoverJumpTableBranches(MF, isThumb);
 }
@@ -3068,7 +3068,7 @@ void CodeViewDebug::endFunctionImpl(const MachineFunction *MF) {
     }
   }
 
-  bool isThumb = Triple(MMI->getModule()->getTargetTriple()).getArch() ==
+  bool isThumb = MMI->getModule()->getTargetTriple().getArch() ==
                  llvm::Triple::ArchType::thumb;
   collectDebugInfoForJumpTables(MF, isThumb);
 
diff --git a/llvm/lib/CodeGen/AssignmentTrackingAnalysis.cpp b/llvm/lib/CodeGen/AssignmentTrackingAnalysis.cpp
index d6ee019383bc8..2bd3211d33304 100644
--- a/llvm/lib/CodeGen/AssignmentTrackingAnalysis.cpp
+++ b/llvm/lib/CodeGen/AssignmentTrackingAnalysis.cpp
@@ -342,8 +342,7 @@ static bool shouldCoalesceFragments(Function &F) {
   // has not been explicitly set and instruction-referencing is turned on.
   switch (CoalesceAdjacentFragmentsOpt) {
   case cl::boolOrDefault::BOU_UNSET:
-    return debuginfoShouldUseDebugInstrRef(
-        Triple(F.getParent()->getTargetTriple()));
+    return debuginfoShouldUseDebugInstrRef(F.getParent()->getTargetTriple());
   case cl::boolOrDefault::BOU_TRUE:
     return true;
   case cl::boolOrDefault::BOU_FALSE:
diff --git a/llvm/lib/CodeGen/GlobalMerge.cpp b/llvm/lib/CodeGen/GlobalMerge.cpp
index 5993fc939a08a..1aedc447935b7 100644
--- a/llvm/lib/CodeGen/GlobalMerge.cpp
+++ b/llvm/lib/CodeGen/GlobalMerge.cpp
@@ -672,7 +672,7 @@ bool GlobalMergeImpl::run(Module &M) {
   if (!EnableGlobalMerge)
     return false;
 
-  IsMachO = Triple(M.getTargetTriple()).isOSBinFormatMachO();
+  IsMachO = M.getTargetTriple().isOSBinFormatMachO();
 
   auto &DL = M.getDataLayout();
   MapVector<std::pair<unsigned, StringRef>, SmallVector<GlobalVariable *, 0>>
diff --git a/llvm/lib/CodeGen/MIRParser/MIRParser.cpp b/llvm/lib/CodeGen/MIRParser/MIRParser.cpp
index b195683051c90..c8fa965fcc2ad 100644
--- a/llvm/lib/CodeGen/MIRParser/MIRParser.cpp
+++ b/llvm/lib/CodeGen/MIRParser/MIRParser.cpp
@@ -253,8 +253,8 @@ MIRParserImpl::parseIRModule(DataLayoutCallbackTy DataLayoutCallback) {
     // Create an empty module when the MIR file is empty.
     NoMIRDocuments = true;
     auto M = std::make_unique<Module>(Filename, Context);
-    if (auto LayoutOverride =
-            DataLayoutCallback(M->getTargetTriple(), M->getDataLayoutStr()))
+    if (auto LayoutOverride = DataLayoutCallback(M->getTargetTriple().str(),
+                                                 M->getDataLayoutStr()))
       M->setDataLayout(*LayoutOverride);
     return M;
   }
@@ -277,8 +277,8 @@ MIRParserImpl::parseIRModule(DataLayoutCallbackTy DataLayoutCallback) {
   } else {
     // Create an new, empty module.
     M = std::make_unique<Module>(Filename, Context);
-    if (auto LayoutOverride =
-            DataLayoutCallback(M->getTargetTriple(), M->getDataLayoutStr()))
+    if (auto LayoutOverride = DataLayoutCallback(M->getTargetTriple().str(),
+                                                 M->getDataLayoutStr()))
       M->setDataLayout(*LayoutOverride);
     NoLLVMIR = true;
   }
diff --git a/llvm/lib/CodeGen/StackProtector.cpp b/llvm/lib/CodeGen/StackProtector.cpp
index 232e84fb672e0..1f76bdcab6f7c 100644
--- a/llvm/lib/CodeGen/StackProtector.cpp
+++ b/llvm/lib/CodeGen/StackProtector.cpp
@@ -217,7 +217,7 @@ static bool ContainsProtectableArray(Type *Ty, Module *M, unsigned SSPBufferSize
       // add stack protectors unless the array is a character array.
       // However, in strong mode any array, regardless of type and size,
       // triggers a protector.
-      if (!Strong && (InStruct || !Triple(M->getTargetTriple()).isOSDarwin()))
+      if (!Strong && (InStruct || !M->getTargetTriple().isOSDarwin()))
         return false;
     }
 
diff --git a/llvm/lib/CodeGen/WinEHPrepare.cpp b/llvm/lib/CodeGen/WinEHPrepare.cpp
index 1970716485613..253a3887009a2 100644
--- a/llvm/lib/CodeGen/WinEHPrepare.cpp
+++ b/llvm/lib/CodeGen/WinEHPrepare.cpp
@@ -406,7 +406,7 @@ static void calculateCXXStateNumbers(WinEHFuncInfo &FuncInfo,
     //  stored in pre-order (outer first, inner next), not post-order
     //  Add to map here.  Fix the CatchHigh after children are processed
     const Module *Mod = BB->getParent()->getParent();
-    bool IsPreOrder = Triple(Mod->getTargetTriple()).isArch64Bit();
+    bool IsPreOrder = Mod->getTargetTriple().isArch64Bit();
     if (IsPreOrder)
       addTryBlockMapEntry(FuncInfo, TryLow, TryHigh, CatchLow, Handlers);
     unsigned TBMEIdx = FuncInfo.TryBlockMap.size() - 1;
diff --git a/llvm/lib/ExecutionEngine/TargetSelect.cpp b/llvm/lib/ExecutionEngine/TargetSelect.cpp
index 72fb16fbf203c..4fe9494649e7e 100644
--- a/llvm/lib/ExecutionEngine/TargetSelect.cpp
+++ b/llvm/lib/ExecutionEngine/TargetSelect.cpp
@@ -29,7 +29,7 @@ TargetMachine *EngineBuilder::selectTarget() {
   // MCJIT can generate code for remote targets, but the old JIT and Interpreter
   // must use the host architecture.
   if (WhichEngine != EngineKind::Interpreter && M)
-    TT.setTriple(M->getTargetTriple());
+    TT = M->getTargetTriple();
 
   return selectTarget(TT, MArch, MCPU, MAttrs);
 }
diff --git a/llvm/lib/Frontend/Offloading/OffloadWrapper.cpp b/llvm/lib/Frontend/Offloading/OffloadWrapper.cpp
index b494c3748ac67..cfddc06fbc00b 100644
--- a/llvm/lib/Frontend/Offloading/OffloadWrapper.cpp
+++ b/llvm/lib/Frontend/Offloading/OffloadWrapper.cpp
@@ -267,7 +267,7 @@ GlobalVariable *createFatbinDesc(Module &M, ArrayRef<char> Image, bool IsHIP,
                                  StringRef Suffix) {
   LLVMContext &C = M.getContext();
   llvm::Type *Int8PtrTy = PointerType::getUnqual(C);
-  llvm::Triple Triple = llvm::Triple(M.getTargetTriple());
+  const llvm::Triple &Triple = M.getTargetTriple();
 
   // Create the global string containing the fatbinary.
   StringRef FatbinConstantSection =
diff --git a/llvm/lib/Frontend/Offloading/Utility.cpp b/llvm/lib/Frontend/Offloading/Utility.cpp
index 5d34bbffe4a75..5dcc16d23004c 100644
--- a/llvm/lib/Frontend/Offloading/Utility.cpp
+++ b/llvm/lib/Frontend/Offloading/Utility.cpp
@@ -41,7 +41,7 @@ offloading::getOffloadingEntryInitializer(Module &M, object::OffloadKind Kind,
                                           Constant *Addr, StringRef Name,
                                           uint64_t Size, uint32_t Flags,
                                           uint64_t Data, Constant *AuxAddr) {
-  llvm::Triple Triple(M.getTargetTriple());
+  const llvm::Triple &Triple = M.getTargetTriple();
   Type *PtrTy = PointerType::getUnqual(M.getContext());
   Type *Int64Ty = Type::getInt64Ty(M.getContext());
   Type *Int32Ty = Type::getInt32Ty(M.getContext());
@@ -87,7 +87,7 @@ void offloading::emitOffloadingEntry(Module &M, object::OffloadKind Kind,
                                      uint64_t Size, uint32_t Flags,
                                      uint64_t Data, Constant *AuxAddr,
                                      StringRef SectionName) {
-  llvm::Triple Triple(M.getTargetTriple());
+  const llvm::Triple &Triple = M.getTargetTriple();
 
   auto [EntryInitializer, NameGV] = getOffloadingEntryInitializer(
       M, Kind, Addr, Name, Size, Flags, Data, AuxAddr);
@@ -110,7 +110,7 @@ void offloading::emitOffloadingEntry(Module &M, object::OffloadKind Kind,
 
 std::pair<GlobalVariable *, GlobalVariable *>
 offloading::getOffloadEntryArray(Module &M, StringRef SectionName) {
-  llvm::Triple Triple(M.getTargetTriple());
+  const llvm::Triple &Triple = M.getTargetTriple();
 
   auto *ZeroInitilaizer =
       ConstantAggregateZero::get(ArrayType::get(getEntryTy(M), 0u));
diff --git a/llvm/lib/Frontend/OpenMP/OMPIRBuilder.cpp b/llvm/lib/Frontend/OpenMP/OMPIRBuilder.cpp
index e34e93442ff85..7ce097269ba8b 100644
--- a/llvm/lib/Frontend/OpenMP/OMPIRBuilder.cpp
+++ b/llvm/lib/Frontend/OpenMP/OMPIRBuilder.cpp
@@ -5511,7 +5511,7 @@ createTargetMachine(Function *F, CodeGenOptLevel OptLevel) {
 
   StringRef CPU = F->getFnAttribute("target-cpu").getValueAsString();
   StringRef Features = F->getFnAttribute("target-features").getValueAsString();
-  const std::string &Triple = M->getTargetTriple();
+  const std::string &Triple = M->getTargetTriple().str();
 
   std::string Error;
   const llvm::Target *TheTarget = TargetRegistry::lookupTarget(Triple, Error);
@@ -7762,7 +7762,7 @@ OpenMPIRBuilder::getOrCreateInternalVariable(Type *Ty, const StringRef &Name,
     // variable for possibly changing that to internal or private, or maybe
     // create different versions of the function for different OMP internal
     // variables.
-    auto Linkage = this->M.getTargetTriple().rfind("wasm32") == 0
+    auto Linkage = this->M.getTargetTriple().getArch() == Triple::wasm32
                        ? GlobalValue::InternalLinkage
                        : GlobalValue::CommonLinkage;
     auto *GV = new GlobalVariable(M, Ty, /*IsConstant=*/false, Linkage,
diff --git a/llvm/lib/IR/AsmWriter.cpp b/llvm/lib/IR/AsmWriter.cpp
index 2ff05a78a92bc..88bb2359cd055 100644
--- a/llvm/lib/IR/AsmWriter.cpp
+++ b/llvm/lib/IR/AsmWriter.cpp
@@ -3039,7 +3039,7 @@ void AssemblyWriter::printModule(const Module *M) {
   if (!DL.empty())
     Out << "target datalayout = \"" << DL << "\"\n";
   if (!M->getTargetTriple().empty())
-    Out << "target triple = \"" << M->getTargetTriple() << "\"\n";
+    Out << "target triple = \"" << M->getTargetTriple().str() << "\"\n";
 
   if (!M->getModuleInlineAsm().empty()) {
     Out << '\n';
diff --git a/llvm/lib/IR/Core.cpp b/llvm/lib/IR/Core.cpp
index 88b89c52c19a2..f4b03e8cb8aa3 100644
--- a/llvm/lib/IR/Core.cpp
+++ b/llvm/lib/IR/Core.cpp
@@ -321,11 +321,11 @@ void LLVMSetDataLayout(LLVMModuleRef M, const char *DataLayoutStr) {
 
 /*--.. Target triple .......................................................--*/
 const char * LLVMGetTarget(LLVMModuleRef M) {
-  return unwrap(M)->getTargetTriple().c_str();
+  return unwrap(M)->getTargetTriple().str().c_str();
 }
 
-void LLVMSetTarget(LLVMModuleRef M, const char *Triple) {
-  unwrap(M)->setTargetTriple(Triple);
+void LLVMSetTarget(LLVMModuleRef M, const char *TripleStr) {
+  unwrap(M)->setTargetTriple(Triple(TripleStr));
 }
 
 /*--.. Module flags ........................................................--*/
diff --git a/llvm/lib/IR/EHPersonalities.cpp b/llvm/lib/IR/EHPersonalities.cpp
index e1f356724baca..9297a82e7d2b0 100644
--- a/llvm/lib/IR/EHPersonalities.cpp
+++ b/llvm/lib/IR/EHPersonalities.cpp
@@ -27,7 +27,7 @@ EHPersonality llvm::classifyEHPersonality(const Value *Pers) {
     return EHPersonality::Unknown;
 
   StringRef Name = F->getName();
-  if (Triple(F->getParent()->getTargetTriple()).isWindowsArm64EC()) {
+  if (F->getParent()->getTargetTriple().isWindowsArm64EC()) {
     // ARM64EC function symbols are mangled by prefixing them with "#".
     // Demangle them by skipping this prefix.
     Name.consume_front("#");
diff --git a/llvm/lib/IR/Globals.cpp b/llvm/lib/IR/Globals.cpp
index 148f8e26535d2..8ca44719a3f94 100644
--- a/llvm/lib/IR/Globals.cpp
+++ b/llvm/lib/IR/Globals.cpp
@@ -359,16 +359,14 @@ bool GlobalObject::canIncreaseAlignment() const {
   // alignment will be incorrect.
 
   // Conservatively assume ELF if there's no parent pointer.
-  bool isELF =
-      (!Parent || Triple(Parent->getTargetTriple()).isOSBinFormatELF());
+  bool isELF = (!Parent || Parent->getTargetTriple().isOSBinFormatELF());
   if (isELF && !isDSOLocal())
     return false;
 
   // GV with toc-data attribute is defined in a TOC entry. To mitigate TOC
   // overflow, the alignment of such symbol should not be increased. Otherwise,
   // padding is needed thus more TOC entries are wasted.
-  bool isXCOFF =
-      (!Parent || Triple(Parent->getTargetTriple()).isOSBinFormatXCOFF());
+  bool isXCOFF = (!Parent || Parent->getTargetTriple().isOSBinFormatXCOFF());
   if (isXCOFF)
     if (const GlobalVariable *GV = dyn_cast<GlobalVariable>(this))
       if (GV->hasAttribute("toc-data"))
diff --git a/llvm/lib/IR/ValueSymbolTable.cpp b/llvm/lib/IR/ValueSymbolTable.cpp
index a020acf22a96c..cd1cee16e7473 100644
--- a/llvm/lib/IR/ValueSymbolTable.cpp
+++ b/llvm/lib/IR/ValueSymbolTable.cpp
@@ -52,7 +52,7 @@ ValueName *ValueSymbolTable::makeUniqueName(Value *V,
     // identifiers. This breaks ABI demangling but at least ptxas accepts and
     // compiles the program.
     const Module *M = GV->getParent();
-    if (!(M && Triple(M->getTargetTriple()).isNVPTX()))
+    if (!(M && M->getTargetTriple().isNVPTX()))
       AppenDot = true;
   }
 
diff --git a/llvm/lib/IR/Verifier.cpp b/llvm/lib/IR/Verifier.cpp
index 3477e2bfe0b2b..e839761f47f1f 100644
--- a/llvm/lib/IR/Verifier.cpp
+++ b/llvm/lib/IR/Verifier.cpp
@@ -153,7 +153,7 @@ struct VerifierSupport {
   bool TreatBrokenDebugInfoAsError = true;
 
   explicit VerifierSupport(raw_ostream *OS, const Module &M)
-      : OS(OS), M(M), MST(&M), TT(Triple::normalize(M.getTargetTriple())),
+      : OS(OS), M(M), MST(&M), TT(M.getTargetTriple().normalize()),
         DL(M.getDataLayout()), Context(M.getContext()) {}
 
 private:
diff --git a/llvm/lib/LTO/LTO.cpp b/llvm/lib/LTO/LTO.cpp
index 0f53c60851217..dfd4b5188907d 100644
--- a/llvm/lib/LTO/LTO.cpp
+++ b/llvm/lib/LTO/LTO.cpp
@@ -733,8 +733,9 @@ Error LTO::add(std::unique_ptr<InputFile> Input,
     writeToResolutionFile(*Conf.ResolutionFile, Input.get(), Res);
 
   if (RegularLTO.CombinedModule->getTargetTriple().empty()) {
-    RegularLTO.CombinedModule->setTargetTriple(Input->getTargetTriple());
-    if (Triple(Input->getTargetTriple()).isOSBinFormatELF())
+    Triple InputTriple(Input->getTargetTriple());
+    RegularLTO.CombinedModule->setTargetTriple(InputTriple);
+    if (InputTriple.isOSBinFormatELF())
       Conf.VisibilityScheme = Config::ELF;
   }
 
diff --git a/llvm/lib/LTO/LTOBackend.cpp b/llvm/lib/LTO/LTOBackend.cpp
index 8a2dddce4892c..d9154ecd5d5e5 100644
--- a/llvm/lib/LTO/LTOBackend.cpp
+++ b/llvm/lib/LTO/LTOBackend.cpp
@@ -202,9 +202,9 @@ static void RegisterPassPlugins(ArrayRef<std::string> PassPlugins,
 
 static std::unique_ptr<TargetMachine>
 createTargetMachine(const Config &Conf, const Target *TheTarget, Module &M) {
-  StringRef TheTriple = M.getTargetTriple();
+  const Triple &TheTriple = M.getTargetTriple();
   SubtargetFeatures Features;
-  Features.getDefaultSubtargetFeatures(Triple(TheTriple));
+  Features.getDefaultSubtargetFeatures(TheTriple);
   for (const std::string &A : Conf.MAttrs)
     Features.AddFeature(A);
 
@@ -222,7 +222,7 @@ createTargetMachine(const Config &Conf, const Target *TheTarget, Module &M) {
     CodeModel = M.getCodeModel();
 
   std::unique_ptr<TargetMachine> TM(TheTarget->createTargetMachine(
-      TheTriple, Conf.CPU, Features.getString(), Conf.Options, RelocModel,
+      TheTriple.str(), Conf.CPU, Features.getString(), Conf.Options, RelocModel,
       CodeModel, Conf.CGOptLevel));
 
   assert(TM && "Failed to create target machine");
@@ -276,7 +276,7 @@ static void runNewPMPasses(const Config &Conf, Module &Mod, TargetMachine *TM,
   RegisterPassPlugins(Conf.PassPlugins, PB);
 
   std::unique_ptr<TargetLibraryInfoImpl> TLII(
-      new TargetLibraryInfoImpl(Triple(TM->getTargetTriple())));
+      new TargetLibraryInfoImpl(TM->getTargetTriple()));
   if (Conf.Freestanding)
     TLII->disableAllFunctions();
   FAM.registerPass([&] { return TargetLibraryAnalysis(*TLII); });
@@ -435,7 +435,7 @@ static void codegen(const Config &Conf, TargetMachine *TM,
   TM->Options.ObjectFilenameForDebug = Stream->ObjectPathName;
 
   legacy::PassManager CodeGenPasses;
-  TargetLibraryInfoImpl TLII(Triple(Mod.getTargetTriple()));
+  TargetLibraryInfoImpl TLII(Mod.getTargetTriple());
   CodeGenPasses.add(new TargetLibraryInfoWrapperPass(TLII));
   // No need to make index available if the module is empty.
   // In theory these passes should not use the index for an empty
@@ -515,12 +515,13 @@ static void splitCodeGen(const Config &C, TargetMachine *TM,
 static Expected<const Target *> initAndLookupTarget(const Config &C,
                                                     Module &Mod) {
   if (!C.OverrideTriple.empty())
-    Mod.setTargetTriple(C.OverrideTriple);
+    Mod.setTargetTriple(Triple(C.OverrideTriple));
   else if (Mod.getTargetTriple().empty())
-    Mod.setTargetTriple(C.DefaultTriple);
+    Mod.setTargetTriple(Triple(C.DefaultTriple));
 
   std::string Msg;
-  const Target *T = TargetRegistry::lookupTarget(Mod.getTargetTriple(), Msg);
+  const Target *T =
+      TargetRegistry::lookupTarget(Mod.getTargetTriple().str(), Msg);
   if (!T)
     return make_error<StringError>(Msg, inconvertibleErrorCode());
   return T;
diff --git a/llvm/lib/LTO/LTOCodeGenerator.cpp b/llvm/lib/LTO/LTOCodeGenerator.cpp
index 774e63899f64b..e855b45915521 100644
--- a/llvm/lib/LTO/LTOCodeGenerator.cpp
+++ b/llvm/lib/LTO/LTOCodeGenerator.cpp
@@ -383,12 +383,12 @@ bool LTOCodeGenerator::determineTarget() {
   if (TargetMach)
     return true;
 
-  TripleStr = MergedModule->getTargetTriple();
+  TripleStr = MergedModule->getTargetTriple().str();
+  llvm::Triple Triple(TripleStr);
   if (TripleStr.empty()) {
     TripleStr = sys::getDefaultTargetTriple();
-    MergedModule->setTargetTriple(TripleStr);
+    MergedModule->setTargetTriple(Triple);
   }
-  llvm::Triple Triple(TripleStr);
 
   // create target machine from info for merged modules
   std::string ErrMsg;
diff --git a/llvm/lib/LTO/LTOModule.cpp b/llvm/lib/LTO/LTOModule.cpp
index 00eb8adb4e103..751615e47631a 100644
--- a/llvm/lib/LTO/LTOModule.cpp
+++ b/llvm/lib/LTO/LTOModule.cpp
@@ -200,7 +200,7 @@ LTOModule::makeLTOModule(MemoryBufferRef Buffer, const TargetOptions &options,
     return EC;
   std::unique_ptr<Module> &M = *MOrErr;
 
-  std::string TripleStr = M->getTargetTriple();
+  std::string TripleStr = M->getTargetTriple().str();
   if (TripleStr.empty())
     TripleStr = sys::getDefaultTargetTriple();
   llvm::Triple Triple(TripleStr);
@@ -691,11 +691,11 @@ const char *LTOModule::getDependentLibrary(lto::InputFile *input, size_t index,
 }
 
 Expected<uint32_t> LTOModule::getMachOCPUType() const {
-  return MachO::getCPUType(Triple(Mod->getTargetTriple()));
+  return MachO::getCPUType(Mod->getTargetTriple());
 }
 
 Expected<uint32_t> LTOModule::getMachOCPUSubType() const {
-  return MachO::getCPUSubType(Triple(Mod->getTargetTriple()));
+  return MachO::getCPUSubType(Mod->getTargetTriple());
 }
 
 bool LTOModule::hasCtorDtor() const {
diff --git a/llvm/lib/LTO/ThinLTOCodeGenerator.cpp b/llvm/lib/LTO/ThinLTOCodeGenerator.cpp
index 189f2876b61c0..aced35f896027 100644
--- a/llvm/lib/LTO/ThinLTOCodeGenerator.cpp
+++ b/llvm/lib/LTO/ThinLTOCodeGenerator.cpp
@@ -252,7 +252,7 @@ static void optimizeModule(Module &TheModule, TargetMachine &TM,
   PassBuilder PB(&TM, PTO, PGOOpt, &PIC);
 
   std::unique_ptr<TargetLibraryInfoImpl> TLII(
-      new TargetLibraryInfoImpl(Triple(TM.getTargetTriple())));
+      new TargetLibraryInfoImpl(TM.getTargetTriple()));
   if (Freestanding)
     TLII->disableAllFunctions();
   FAM.registerPass([&] { return TargetLibraryAnalysis(*TLII); });
@@ -677,7 +677,7 @@ void ThinLTOCodeGenerator::promote(Module &TheModule, ModuleSummaryIndex &Index,
 
   // Convert the preserved symbols set from string to GUID
   auto GUIDPreservedSymbols = computeGUIDPreservedSymbols(
-      File, PreservedSymbols, Triple(TheModule.getTargetTriple()));
+      File, PreservedSymbols, TheModule.getTargetTriple());
 
   // Add used symbol to the preserved symbols.
   addUsedSymbolToPreservedGUID(File, GUIDPreservedSymbols);
@@ -730,7 +730,7 @@ void ThinLTOCodeGenerator::crossModuleImport(Module &TheModule,
 
   // Convert the preserved symbols set from string to GUID
   auto GUIDPreservedSymbols = computeGUIDPreservedSymbols(
-      File, PreservedSymbols, Triple(TheModule.getTargetTriple()));
+      File, PreservedSymbols, TheModule.getTargetTriple());
 
   addUsedSymbolToPreservedGUID(File, GUIDPreservedSymbols);
 
@@ -770,7 +770,7 @@ void ThinLTOCodeGenerator::gatherImportedSummariesForModule(
 
   // Convert the preserved symbols set from string to GUID
   auto GUIDPreservedSymbols = computeGUIDPreservedSymbols(
-      File, PreservedSymbols, Triple(TheModule.getTargetTriple()));
+      File, PreservedSymbols, TheModule.getTargetTriple());
 
   addUsedSymbolToPreservedGUID(File, GUIDPreservedSymbols);
 
@@ -808,7 +808,7 @@ void ThinLTOCodeGenerator::emitImports(Module &TheModule, StringRef OutputName,
 
   // Convert the preserved symbols set from string to GUID
   auto GUIDPreservedSymbols = computeGUIDPreservedSymbols(
-      File, PreservedSymbols, Triple(TheModule.getTargetTriple()));
+      File, PreservedSymbols, TheModule.getTargetTriple());
 
   addUsedSymbolToPreservedGUID(File, GUIDPreservedSymbols);
 
@@ -848,7 +848,7 @@ void ThinLTOCodeGenerator::emitImports(Module &TheModule, StringRef OutputName,
 void ThinLTOCodeGenerator::internalize(Module &TheModule,
                                        ModuleSummaryIndex &Index,
                                        const lto::InputFile &File) {
-  initTMBuilder(TMBuilder, Triple(TheModule.getTargetTriple()));
+  initTMBuilder(TMBuilder, TheModule.getTargetTriple());
   auto ModuleCount = Index.modulePaths().size();
   auto ModuleIdentifier = TheModule.getModuleIdentifier();
 
@@ -909,7 +909,7 @@ void ThinLTOCodeGenerator::internalize(Module &TheModule,
  * Perform post-importing ThinLTO optimizations.
  */
 void ThinLTOCodeGenerator::optimize(Module &TheModule) {
-  initTMBuilder(TMBuilder, Triple(TheModule.getTargetTriple()));
+  initTMBuilder(TMBuilder, TheModule.getTargetTriple());
 
   // Optimize now
   optimizeModule(TheModule, *TMBuilder.create(), OptLevel, Freestanding,
diff --git a/llvm/lib/LTO/UpdateCompilerUsed.cpp b/llvm/lib/LTO/UpdateCompilerUsed.cpp
index 2882ea9d14b23..c95aaaf30bf80 100644
--- a/llvm/lib/LTO/UpdateCompilerUsed.cpp
+++ b/llvm/lib/LTO/UpdateCompilerUsed.cpp
@@ -57,7 +57,7 @@ class PreserveLibCallsAndAsmUsed {
   // same names are added to llvm.compiler.used to prevent them from being
   // deleted by optimizations.
   void initializeLibCalls(const Module &TheModule) {
-    TargetLibraryInfoImpl TLII(Triple(TM.getTargetTriple()));
+    TargetLibraryInfoImpl TLII(TM.getTargetTriple());
     TargetLibraryInfo TLI(TLII);
 
     // TargetLibraryInfo has info on C runtime library calls on the current
diff --git a/llvm/lib/Linker/IRMover.cpp b/llvm/lib/Linker/IRMover.cpp
index 62e2af4da57bb..e732367b5127e 100644
--- a/llvm/lib/Linker/IRMover.cpp
+++ b/llvm/lib/Linker/IRMover.cpp
@@ -1586,11 +1586,11 @@ Error IRLinker::run() {
       !SrcTriple.isCompatibleWith(DstTriple))
     emitWarning("Linking two modules of different target triples: '" +
                 SrcM->getModuleIdentifier() + "' is '" +
-                SrcM->getTargetTriple() + "' whereas '" +
-                DstM.getModuleIdentifier() + "' is '" + DstM.getTargetTriple() +
-                "'\n");
+                SrcM->getTargetTriple().str() + "' whereas '" +
+                DstM.getModuleIdentifier() + "' is '" +
+                DstM.getTargetTriple().str() + "'\n");
 
-  DstM.setTargetTriple(SrcTriple.merge(DstTriple));
+  DstM.setTargetTriple(Triple(SrcTriple.merge(DstTriple)));
 
   // Loop over all of the linked values to compute type mappings.
   computeTypeMapping();
diff --git a/llvm/lib/Object/IRObjectFile.cpp b/llvm/lib/Object/IRObjectFile.cpp
index cd93a84fc6fa0..167fc27cf74ef 100644
--- a/llvm/lib/Object/IRObjectFile.cpp
+++ b/llvm/lib/Object/IRObjectFile.cpp
@@ -66,7 +66,7 @@ basic_symbol_iterator IRObjectFile::symbol_end() const {
 StringRef IRObjectFile::getTargetTriple() const {
   // Each module must have the same target triple, so we arbitrarily access the
   // first one.
-  return Mods[0]->getTargetTriple();
+  return Mods[0]->getTargetTriple().str();
 }
 
 Expected<MemoryBufferRef>
diff --git a/llvm/lib/Object/IRSymtab.cpp b/llvm/lib/Object/IRSymtab.cpp
index 2a2b235461a55..2e818be334a5e 100644
--- a/llvm/lib/Object/IRSymtab.cpp
+++ b/llvm/lib/Object/IRSymtab.cpp
@@ -281,8 +281,7 @@ Error Builder::addSymbol(const ModuleSymbolTable &Msymtab,
   setStr(Sym.IRName, GV->getName());
 
   static const DenseSet<StringRef> PreservedSymbolsSet =
-      buildPreservedSymbolsSet(
-          llvm::Triple(GV->getParent()->getTargetTriple()));
+      buildPreservedSymbolsSet(GV->getParent()->getTargetTriple());
   bool IsPreservedSymbol = PreservedSymbolsSet.contains(GV->getName());
 
   if (Used.count(GV) || IsPreservedSymbol)
@@ -350,9 +349,9 @@ Error Builder::build(ArrayRef<Module *> IRMods) {
   assert(!IRMods.empty());
   Hdr.Version = storage::Header::kCurrentVersion;
   setStr(Hdr.Producer, kExpectedProducerName);
-  setStr(Hdr.TargetTriple, IRMods[0]->getTargetTriple());
+  setStr(Hdr.TargetTriple, IRMods[0]->getTargetTriple().str());
   setStr(Hdr.SourceFileName, IRMods[0]->getSourceFileName());
-  TT = Triple(IRMods[0]->getTargetTriple());
+  TT = IRMods[0]->getTargetTriple();
 
   for (auto *M : IRMods)
     if (Error Err = addModule(M))
diff --git a/llvm/lib/ProfileData/InstrProf.cpp b/llvm/lib/ProfileData/InstrProf.cpp
index 47eb751328b51..6abfe4c244ca9 100644
--- a/llvm/lib/ProfileData/InstrProf.cpp
+++ b/llvm/lib/ProfileData/InstrProf.cpp
@@ -438,7 +438,7 @@ std::string getPGOFuncNameVarName(StringRef FuncName,
 }
 
 bool isGPUProfTarget(const Module &M) {
-  const auto &T = Triple(M.getTargetTriple());
+  const Triple &T = M.getTargetTriple();
   return T.isAMDGPU() || T.isNVPTX();
 }
 
@@ -1437,7 +1437,7 @@ bool needsComdatForCounter(const GlobalObject &GO, const Module &M) {
   if (GO.hasComdat())
     return true;
 
-  if (!Triple(M.getTargetTriple()).supportsCOMDAT())
+  if (!M.getTargetTriple().supportsCOMDAT())
     return false;
 
   // See createPGOFuncNameVar for more details. To avoid link errors, profile
diff --git a/llvm/lib/Target/AArch64/AArch64Arm64ECCallLowering.cpp b/llvm/lib/Target/AArch64/AArch64Arm64ECCallLowering.cpp
index ee468a40d643c..066d62b3d4b4b 100644
--- a/llvm/lib/Target/AArch64/AArch64Arm64ECCallLowering.cpp
+++ b/llvm/lib/Target/AArch64/AArch64Arm64ECCallLowering.cpp
@@ -741,7 +741,7 @@ AArch64Arm64ECCallLowering::buildPatchableThunk(GlobalAlias *UnmangledAlias,
 
 // Lower an indirect call with inline code.
 void AArch64Arm64ECCallLowering::lowerCall(CallBase *CB) {
-  assert(Triple(CB->getModule()->getTargetTriple()).isOSWindows() &&
+  assert(CB->getModule()->getTargetTriple().isOSWindows() &&
          "Only applicable for Windows targets");
 
   IRBuilder<> B(CB);
diff --git a/llvm/lib/Target/AArch64/AArch64MachineFunctionInfo.cpp b/llvm/lib/Target/AArch64/AArch64MachineFunctionInfo.cpp
index f08506979a1ae..5bcff61cef4b1 100644
--- a/llvm/lib/Target/AArch64/AArch64MachineFunctionInfo.cpp
+++ b/llvm/lib/Target/AArch64/AArch64MachineFunctionInfo.cpp
@@ -74,7 +74,7 @@ static bool ShouldSignWithBKey(const Function &F, const AArch64Subtarget &STI) {
 
 static bool hasELFSignedGOTHelper(const Function &F,
                                   const AArch64Subtarget *STI) {
-  if (!Triple(STI->getTargetTriple()).isOSBinFormatELF())
+  if (!STI->getTargetTriple().isOSBinFormatELF())
     return false;
   const Module *M = F.getParent();
   const auto *Flag = mdconst::extract_or_null<ConstantInt>(
diff --git a/llvm/lib/Target/AArch64/AArch64StackTagging.cpp b/llvm/lib/Target/AArch64/AArch64StackTagging.cpp
index fad83bbebd5d9..54327b3f15944 100644
--- a/llvm/lib/Target/AArch64/AArch64StackTagging.cpp
+++ b/llvm/lib/Target/AArch64/AArch64StackTagging.cpp
@@ -430,8 +430,7 @@ void AArch64StackTagging::tagAlloca(AllocaInst *AI, Instruction *InsertBefore,
                                                     Intrinsic::aarch64_stgp);
 
   InitializerBuilder IB(Size, DL, Ptr, SetTagFunc, SetTagZeroFunc, StgpFunc);
-  bool LittleEndian =
-      Triple(AI->getModule()->getTargetTriple()).isLittleEndian();
+  bool LittleEndian = AI->getModule()->getTargetTriple().isLittleEndian();
   // Current implementation of initializer merging assumes little endianness.
   if (MergeInit && !F->hasOptNone() && LittleEndian &&
       Size < ClMergeInitSizeLimit) {
@@ -473,7 +472,7 @@ Instruction *AArch64StackTagging::insertBaseTaggedPointer(
       IRB.CreateIntrinsic(Intrinsic::aarch64_irg_sp, {},
                           {Constant::getNullValue(IRB.getInt64Ty())});
   Base->setName("basetag");
-  auto TargetTriple = Triple(M.getTargetTriple());
+  const Triple &TargetTriple = M.getTargetTriple();
   // This ABI will make it into Android API level 35.
   // The ThreadLong format is the same as with HWASan, but the entries for
   // stack MTE take two slots (16 bytes).
diff --git a/llvm/lib/Target/AMDGPU/AMDGPUSwLowerLDS.cpp b/llvm/lib/Target/AMDGPU/AMDGPUSwLowerLDS.cpp
index 6ba7920e9f00c..2a41f7cad1f00 100644
--- a/llvm/lib/Target/AMDGPU/AMDGPUSwLowerLDS.cpp
+++ b/llvm/lib/Target/AMDGPU/AMDGPUSwLowerLDS.cpp
@@ -1129,8 +1129,8 @@ void AMDGPUSwLowerLDS::initAsanInfo() {
   uint64_t Offset;
   int Scale;
   bool OrShadowOffset;
-  llvm::getAddressSanitizerParams(Triple(AMDGPUTM.getTargetTriple()), LongSize,
-                                  false, &Offset, &Scale, &OrShadowOffset);
+  llvm::getAddressSanitizerParams(AMDGPUTM.getTargetTriple(), LongSize, false,
+                                  &Offset, &Scale, &OrShadowOffset);
   AsanInfo.Scale = Scale;
   AsanInfo.Offset = Offset;
 }
diff --git a/llvm/lib/Target/DirectX/DXILOpBuilder.cpp b/llvm/lib/Target/DirectX/DXILOpBuilder.cpp
index e76b7d6ad7891..39678d05393ce 100644
--- a/llvm/lib/Target/DirectX/DXILOpBuilder.cpp
+++ b/llvm/lib/Target/DirectX/DXILOpBuilder.cpp
@@ -463,7 +463,7 @@ namespace dxil {
 // would have been done at the time the module M is constructed in the earlier
 // stages of compilation.
 DXILOpBuilder::DXILOpBuilder(Module &M) : M(M), IRB(M.getContext()) {
-  Triple TT(Triple(M.getTargetTriple()));
+  const Triple &TT = M.getTargetTriple();
   DXILVersion = TT.getDXILVersion();
   ShaderStage = TT.getEnvironment();
   // Ensure Environment type is known
diff --git a/llvm/lib/Target/DirectX/DXILOpLowering.cpp b/llvm/lib/Target/DirectX/DXILOpLowering.cpp
index bc41347faf06c..92b6787b9571e 100644
--- a/llvm/lib/Target/DirectX/DXILOpLowering.cpp
+++ b/llvm/lib/Target/DirectX/DXILOpLowering.cpp
@@ -358,7 +358,7 @@ class OpLowerer {
   /// model and taking into account binding information from
   /// DXILResourceBindingAnalysis.
   bool lowerHandleFromBinding(Function &F) {
-    Triple TT(Triple(M.getTargetTriple()));
+    const Triple &TT = M.getTargetTriple();
     if (TT.getDXILVersion() < VersionTuple(1, 6))
       return lowerToCreateHandle(F);
     return lowerToBindAndAnnotateHandle(F);
@@ -528,7 +528,7 @@ class OpLowerer {
   }
 
   [[nodiscard]] bool lowerRawBufferLoad(Function &F) {
-    Triple TT(Triple(M.getTargetTriple()));
+    const Triple &TT = M.getTargetTriple();
     VersionTuple DXILVersion = TT.getDXILVersion();
     const DataLayout &DL = F.getDataLayout();
     IRBuilder<> &IRB = OpBuilder.getIRB();
@@ -628,7 +628,7 @@ class OpLowerer {
   }
 
   [[nodiscard]] bool lowerBufferStore(Function &F, bool IsRaw) {
-    Triple TT(Triple(M.getTargetTriple()));
+    const Triple &TT = M.getTargetTriple();
     VersionTuple DXILVersion = TT.getDXILVersion();
     const DataLayout &DL = F.getDataLayout();
     IRBuilder<> &IRB = OpBuilder.getIRB();
diff --git a/llvm/lib/Target/DirectX/DXILWriter/DXILBitcodeWriter.cpp b/llvm/lib/Target/DirectX/DXILWriter/DXILBitcodeWriter.cpp
index 1eca84662317b..ea33ee5759cb7 100644
--- a/llvm/lib/Target/DirectX/DXILWriter/DXILBitcodeWriter.cpp
+++ b/llvm/lib/Target/DirectX/DXILWriter/DXILBitcodeWriter.cpp
@@ -1161,8 +1161,8 @@ void DXILBitcodeWriter::writeValueSymbolTableForwardDecl() {}
 void DXILBitcodeWriter::writeModuleInfo() {
   // Emit various pieces of data attached to a module.
   if (!M.getTargetTriple().empty())
-    writeStringRecord(Stream, bitc::MODULE_CODE_TRIPLE, M.getTargetTriple(),
-                      0 /*TODO*/);
+    writeStringRecord(Stream, bitc::MODULE_CODE_TRIPLE,
+                      M.getTargetTriple().str(), 0 /*TODO*/);
   const std::string &DL = M.getDataLayoutStr();
   if (!DL.empty())
     writeStringRecord(Stream, bitc::MODULE_CODE_DATALAYOUT, DL, 0 /*TODO*/);
diff --git a/llvm/lib/Target/DirectX/DXILWriter/DXILWriterPass.cpp b/llvm/lib/Target/DirectX/DXILWriter/DXILWriterPass.cpp
index b0a71003bcf32..dfc79039cb54e 100644
--- a/llvm/lib/Target/DirectX/DXILWriter/DXILWriterPass.cpp
+++ b/llvm/lib/Target/DirectX/DXILWriter/DXILWriterPass.cpp
@@ -65,10 +65,10 @@ class EmbedDXILPass : public llvm::ModulePass {
     std::string Data;
     llvm::raw_string_ostream OS(Data);
 
-    const std::string OriginalTriple = M.getTargetTriple();
+    Triple OriginalTriple = M.getTargetTriple();
     // Set to DXIL triple when write to bitcode.
     // Only the output bitcode need to be DXIL triple.
-    M.setTargetTriple("dxil-ms-dx");
+    M.setTargetTriple(Triple("dxil-ms-dx"));
 
     WriteDXILToFile(M, OS);
 
diff --git a/llvm/lib/Target/Hexagon/HexagonLoopIdiomRecognition.cpp b/llvm/lib/Target/Hexagon/HexagonLoopIdiomRecognition.cpp
index 41803e66a0f8e..3df2bed0ca96e 100644
--- a/llvm/lib/Target/Hexagon/HexagonLoopIdiomRecognition.cpp
+++ b/llvm/lib/Target/Hexagon/HexagonLoopIdiomRecognition.cpp
@@ -2406,7 +2406,7 @@ bool HexagonLoopIdiomRecognize::runOnCountableLoop(Loop *L) {
 
 bool HexagonLoopIdiomRecognize::run(Loop *L) {
   const Module &M = *L->getHeader()->getParent()->getParent();
-  if (Triple(M.getTargetTriple()).getArch() != Triple::hexagon)
+  if (M.getTargetTriple().getArch() != Triple::hexagon)
     return false;
 
   // If the loop could not be converted to canonical form, it must have an
diff --git a/llvm/lib/Target/Mips/AsmParser/MipsAsmParser.cpp b/llvm/lib/Target/Mips/AsmParser/MipsAsmParser.cpp
index 62f17675f8230..65ca5d860f937 100644
--- a/llvm/lib/Target/Mips/AsmParser/MipsAsmParser.cpp
+++ b/llvm/lib/Target/Mips/AsmParser/MipsAsmParser.cpp
@@ -523,9 +523,9 @@ class MipsAsmParser : public MCTargetAsmParser {
 
   MipsAsmParser(const MCSubtargetInfo &sti, MCAsmParser &parser,
                 const MCInstrInfo &MII, const MCTargetOptions &Options)
-    : MCTargetAsmParser(Options, sti, MII),
-        ABI(MipsABIInfo::computeTargetABI(Triple(sti.getTargetTriple()),
-                                          sti.getCPU(), Options)) {
+      : MCTargetAsmParser(Options, sti, MII),
+        ABI(MipsABIInfo::computeTargetABI(sti.getTargetTriple(), sti.getCPU(),
+                                          Options)) {
     MCAsmParserExtension::Initialize(parser);
 
     parser.addAliasForDirective(".asciiz", ".asciz");
diff --git a/llvm/lib/Target/SPIRV/SPIRVAPI.cpp b/llvm/lib/Target/SPIRV/SPIRVAPI.cpp
index a19384d4e279c..759a403a804c7 100644
--- a/llvm/lib/Target/SPIRV/SPIRVAPI.cpp
+++ b/llvm/lib/Target/SPIRV/SPIRVAPI.cpp
@@ -79,7 +79,7 @@ SPIRVTranslate(Module *M, std::string &SpirvObj, std::string &ErrMsg,
 
   if (TargetTriple.getTriple().empty()) {
     TargetTriple.setTriple(DefaultTriple);
-    M->setTargetTriple(DefaultTriple);
+    M->setTargetTriple(Triple(DefaultTriple));
   }
   const Target *TheTarget =
       TargetRegistry::lookupTarget(DefaultMArch, TargetTriple, ErrMsg);
@@ -118,7 +118,7 @@ SPIRVTranslate(Module *M, std::string &SpirvObj, std::string &ErrMsg,
   }
   M->setDataLayout(MaybeDL.get());
 
-  TargetLibraryInfoImpl TLII(Triple(M->getTargetTriple()));
+  TargetLibraryInfoImpl TLII(M->getTargetTriple());
   legacy::PassManager PM;
   PM.add(new TargetLibraryInfoWrapperPass(TLII));
   std::unique_ptr<MachineModuleInfoWrapperPass> MMIWP(
@@ -148,9 +148,9 @@ SPIRVTranslateModule(Module *M, std::string &SpirvObj, std::string &ErrMsg,
                      const std::vector<std::string> &Opts) {
   // optional: Opts[0] is a string representation of Triple,
   // take Module triple otherwise
-  Triple TargetTriple(Opts.empty() || Opts[0].empty()
-                          ? M->getTargetTriple()
-                          : Triple::normalize(Opts[0]));
+  Triple TargetTriple = Opts.empty() || Opts[0].empty()
+                            ? M->getTargetTriple()
+                            : Triple(Triple::normalize(Opts[0]));
   // optional: Opts[1] is a string representation of CodeGenOptLevel,
   // no optimization otherwise
   llvm::CodeGenOptLevel OLevel = CodeGenOptLevel::None;
diff --git a/llvm/lib/Target/X86/X86MCInstLower.cpp b/llvm/lib/Target/X86/X86MCInstLower.cpp
index 0f8fbf5be1c95..bc4e0ac689753 100644
--- a/llvm/lib/Target/X86/X86MCInstLower.cpp
+++ b/llvm/lib/Target/X86/X86MCInstLower.cpp
@@ -959,9 +959,8 @@ void X86AsmPrinter::LowerASAN_CHECK_MEMACCESS(const MachineInstr &MI) {
   uint64_t ShadowBase;
   int MappingScale;
   bool OrShadowOffset;
-  getAddressSanitizerParams(Triple(TM.getTargetTriple()), 64,
-                            AccessInfo.CompileKernel, &ShadowBase,
-                            &MappingScale, &OrShadowOffset);
+  getAddressSanitizerParams(TM.getTargetTriple(), 64, AccessInfo.CompileKernel,
+                            &ShadowBase, &MappingScale, &OrShadowOffset);
 
   StringRef Name = AccessInfo.IsWrite ? "store" : "load";
   StringRef Op = OrShadowOffset ? "or" : "add";
diff --git a/llvm/lib/Transforms/CFGuard/CFGuard.cpp b/llvm/lib/Transforms/CFGuard/CFGuard.cpp
index 41d68b62eb8d7..45c2a3394da02 100644
--- a/llvm/lib/Transforms/CFGuard/CFGuard.cpp
+++ b/llvm/lib/Transforms/CFGuard/CFGuard.cpp
@@ -171,7 +171,7 @@ class CFGuard : public FunctionPass {
 
 void CFGuardImpl::insertCFGuardCheck(CallBase *CB) {
 
-  assert(Triple(CB->getModule()->getTargetTriple()).isOSWindows() &&
+  assert(CB->getModule()->getTargetTriple().isOSWindows() &&
          "Only applicable for Windows targets");
   assert(CB->isIndirectCall() &&
          "Control Flow Guard checks can only be added to indirect calls");
@@ -200,7 +200,7 @@ void CFGuardImpl::insertCFGuardCheck(CallBase *CB) {
 
 void CFGuardImpl::insertCFGuardDispatch(CallBase *CB) {
 
-  assert(Triple(CB->getModule()->getTargetTriple()).isOSWindows() &&
+  assert(CB->getModule()->getTargetTriple().isOSWindows() &&
          "Only applicable for Windows targets");
   assert(CB->isIndirectCall() &&
          "Control Flow Guard checks can only be added to indirect calls");
diff --git a/llvm/lib/Transforms/Coroutines/CoroSplit.cpp b/llvm/lib/Transforms/Coroutines/CoroSplit.cpp
index e1f767edd6ee1..be35ef99261ed 100644
--- a/llvm/lib/Transforms/Coroutines/CoroSplit.cpp
+++ b/llvm/lib/Transforms/Coroutines/CoroSplit.cpp
@@ -659,8 +659,7 @@ void coro::BaseCloner::salvageDebugInfo() {
   SmallDenseMap<Argument *, AllocaInst *, 4> ArgToAllocaMap;
 
   // Only 64-bit ABIs have a register we can refer to with the entry value.
-  bool UseEntryValue =
-      llvm::Triple(OrigF.getParent()->getTargetTriple()).isArch64Bit();
+  bool UseEntryValue = OrigF.getParent()->getTargetTriple().isArch64Bit();
   for (DbgVariableIntrinsic *DVI : Worklist)
     coro::salvageDebugInfo(ArgToAllocaMap, *DVI, UseEntryValue);
   for (DbgVariableRecord *DVR : DbgVariableRecords)
diff --git a/llvm/lib/Transforms/IPO/Internalize.cpp b/llvm/lib/Transforms/IPO/Internalize.cpp
index 404102eef89fc..4b690bf2b2fc1 100644
--- a/llvm/lib/Transforms/IPO/Internalize.cpp
+++ b/llvm/lib/Transforms/IPO/Internalize.cpp
@@ -228,17 +228,17 @@ bool InternalizePass::internalizeModule(Module &M) {
   // FIXME: We should probably add this (and the __stack_chk_guard) via some
   // type of call-back in CodeGen.
   AlwaysPreserved.insert("__stack_chk_fail");
-  if (Triple(M.getTargetTriple()).isOSAIX())
+  if (M.getTargetTriple().isOSAIX())
     AlwaysPreserved.insert("__ssp_canary_word");
   else
     AlwaysPreserved.insert("__stack_chk_guard");
 
   // Preserve the RPC interface for GPU host callbacks when internalizing.
-  if (Triple(M.getTargetTriple()).isNVPTX())
+  if (M.getTargetTriple().isNVPTX())
     AlwaysPreserved.insert("__llvm_rpc_client");
 
   // Mark all functions not in the api as internal.
-  IsWasm = Triple(M.getTargetTriple()).isOSBinFormatWasm();
+  IsWasm = M.getTargetTriple().isOSBinFormatWasm();
   for (Function &I : M) {
     if (!maybeInternalize(I, ComdatMap))
       continue;
diff --git a/llvm/lib/Transforms/Instrumentation/AddressSanitizer.cpp b/llvm/lib/Transforms/Instrumentation/AddressSanitizer.cpp
index 8d8d56035a48f..b5e9cde2ba5f6 100644
--- a/llvm/lib/Transforms/Instrumentation/AddressSanitizer.cpp
+++ b/llvm/lib/Transforms/Instrumentation/AddressSanitizer.cpp
@@ -744,7 +744,7 @@ struct AddressSanitizer {
     IntptrTy = Type::getIntNTy(*C, LongSize);
     PtrTy = PointerType::getUnqual(*C);
     Int32Ty = Type::getInt32Ty(*C);
-    TargetTriple = Triple(M.getTargetTriple());
+    TargetTriple = M.getTargetTriple();
 
     Mapping = getShadowMapping(TargetTriple, LongSize, this->CompileKernel);
 
@@ -905,7 +905,7 @@ class ModuleAddressSanitizer {
     int LongSize = M.getDataLayout().getPointerSizeInBits();
     IntptrTy = Type::getIntNTy(*C, LongSize);
     PtrTy = PointerType::getUnqual(*C);
-    TargetTriple = Triple(M.getTargetTriple());
+    TargetTriple = M.getTargetTriple();
     Mapping = getShadowMapping(TargetTriple, LongSize, this->CompileKernel);
 
     if (ClOverrideDestructorKind != AsanDtorKind::Invalid)
@@ -1038,8 +1038,7 @@ struct FunctionStackPoisoner : public InstVisitor<FunctionStackPoisoner> {
         IntptrTy(ASan.IntptrTy),
         IntptrPtrTy(PointerType::get(IntptrTy->getContext(), 0)),
         Mapping(ASan.Mapping),
-        PoisonStack(ClStack &&
-                    !Triple(F.getParent()->getTargetTriple()).isAMDGPU()) {}
+        PoisonStack(ClStack && !F.getParent()->getTargetTriple().isAMDGPU()) {}
 
   bool runOnFunction() {
     if (!PoisonStack)
@@ -2710,7 +2709,7 @@ ModuleAddressSanitizer::getRedzoneSizeForGlobal(uint64_t SizeInBytes) const {
 
 int ModuleAddressSanitizer::GetAsanVersion() const {
   int LongSize = M.getDataLayout().getPointerSizeInBits();
-  bool isAndroid = Triple(M.getTargetTriple()).isAndroid();
+  bool isAndroid = M.getTargetTriple().isAndroid();
   int Version = 8;
   // 32-bit Android is one version ahead because of the switch to dynamic
   // shadow.
diff --git a/llvm/lib/Transforms/Instrumentation/GCOVProfiling.cpp b/llvm/lib/Transforms/Instrumentation/GCOVProfiling.cpp
index 5e204d7362372..86c263f5b2154 100644
--- a/llvm/lib/Transforms/Instrumentation/GCOVProfiling.cpp
+++ b/llvm/lib/Transforms/Instrumentation/GCOVProfiling.cpp
@@ -904,7 +904,7 @@ bool GCOVProfiler::emitProfileNotes(
         GlobalVariable *Counters = new GlobalVariable(
             *M, CounterTy, false, GlobalValue::InternalLinkage,
             Constant::getNullValue(CounterTy), "__llvm_gcov_ctr");
-        const llvm::Triple &Triple = llvm::Triple(M->getTargetTriple());
+        const llvm::Triple &Triple = M->getTargetTriple();
         if (Triple.getObjectFormat() == llvm::Triple::XCOFF)
           Counters->setSection("__llvm_gcov_ctr_section");
         CountersBySP.emplace_back(Counters, SP);
@@ -971,7 +971,7 @@ bool GCOVProfiler::emitProfileNotes(
     }
 
     if (EmitGCDA) {
-      const llvm::Triple &Triple = llvm::Triple(M->getTargetTriple());
+      const llvm::Triple &Triple = M->getTargetTriple();
       if (Triple.getObjectFormat() == llvm::Triple::XCOFF)
         emitModuleInitFunctionPtrs(CountersBySP);
       else
@@ -1053,7 +1053,7 @@ void GCOVProfiler::emitModuleInitFunctionPtrs(
   CovInitGV->setInitializer(ConstantStruct::get(STy, InitFuncPtrs));
   CovInitGV->setVisibility(GlobalValue::VisibilityTypes::DefaultVisibility);
   CovInitGV->setSection(getInstrProfSectionName(
-      IPSK_covinit, Triple(M->getTargetTriple()).getObjectFormat()));
+      IPSK_covinit, M->getTargetTriple().getObjectFormat()));
   CovInitGV->setAlignment(Align(INSTR_PROF_DATA_ALIGNMENT));
   CovInitGV->setConstant(true);
 }
diff --git a/llvm/lib/Transforms/Instrumentation/HWAddressSanitizer.cpp b/llvm/lib/Transforms/Instrumentation/HWAddressSanitizer.cpp
index a3423912d4f31..e0e906d1eef7c 100644
--- a/llvm/lib/Transforms/Instrumentation/HWAddressSanitizer.cpp
+++ b/llvm/lib/Transforms/Instrumentation/HWAddressSanitizer.cpp
@@ -489,7 +489,7 @@ PreservedAnalyses HWAddressSanitizerPass::run(Module &M,
   if (checkIfAlreadyInstrumented(M, "nosanitize_hwaddress"))
     return PreservedAnalyses::all();
   const StackSafetyGlobalInfo *SSI = nullptr;
-  auto TargetTriple = llvm::Triple(M.getTargetTriple());
+  const Triple &TargetTriple = M.getTargetTriple();
   if (shouldUseStackSafetyAnalysis(TargetTriple, Options.DisableOptimization))
     SSI = &MAM.getResult<StackSafetyGlobalAnalysis>(M);
 
@@ -665,7 +665,7 @@ void HWAddressSanitizer::removeFnAttributes(Function *F) {
 /// inserts a call to __hwasan_init to the module's constructor list.
 void HWAddressSanitizer::initializeModule() {
   LLVM_DEBUG(dbgs() << "Init " << M.getName() << "\n");
-  TargetTriple = Triple(M.getTargetTriple());
+  TargetTriple = M.getTargetTriple();
 
   for (Function &F : M.functions())
     removeFnAttributes(&F);
diff --git a/llvm/lib/Transforms/Instrumentation/InstrOrderFile.cpp b/llvm/lib/Transforms/Instrumentation/InstrOrderFile.cpp
index fe03de1b0e877..f701df0002e7c 100644
--- a/llvm/lib/Transforms/Instrumentation/InstrOrderFile.cpp
+++ b/llvm/lib/Transforms/Instrumentation/InstrOrderFile.cpp
@@ -69,7 +69,7 @@ struct InstrOrderFile {
     std::string SymbolName = INSTR_PROF_ORDERFILE_BUFFER_NAME_STR;
     OrderFileBuffer = new GlobalVariable(M, BufferTy, false, GlobalValue::LinkOnceODRLinkage,
                            Constant::getNullValue(BufferTy), SymbolName);
-    Triple TT = Triple(M.getTargetTriple());
+    const Triple &TT = M.getTargetTriple();
     OrderFileBuffer->setSection(
         getInstrProfSectionName(IPSK_orderfile, TT.getObjectFormat()));
 
diff --git a/llvm/lib/Transforms/Instrumentation/InstrProfiling.cpp b/llvm/lib/Transforms/Instrumentation/InstrProfiling.cpp
index 54b328b79a641..008c1faf0a0c3 100644
--- a/llvm/lib/Transforms/Instrumentation/InstrProfiling.cpp
+++ b/llvm/lib/Transforms/Instrumentation/InstrProfiling.cpp
@@ -253,7 +253,7 @@ class InstrLowerer final {
   InstrLowerer(Module &M, const InstrProfOptions &Options,
                std::function<const TargetLibraryInfo &(Function &F)> GetTLI,
                bool IsCS)
-      : M(M), Options(Options), TT(Triple(M.getTargetTriple())), IsCS(IsCS),
+      : M(M), Options(Options), TT(M.getTargetTriple()), IsCS(IsCS),
         GetTLI(GetTLI), DataReferencedByCode(profDataReferencedByCode(M)) {}
 
   bool lower();
diff --git a/llvm/lib/Transforms/Instrumentation/MemProfiler.cpp b/llvm/lib/Transforms/Instrumentation/MemProfiler.cpp
index 71a0b29f82a7e..8da299e296c31 100644
--- a/llvm/lib/Transforms/Instrumentation/MemProfiler.cpp
+++ b/llvm/lib/Transforms/Instrumentation/MemProfiler.cpp
@@ -283,7 +283,7 @@ class MemProfiler {
 
 class ModuleMemProfiler {
 public:
-  ModuleMemProfiler(Module &M) { TargetTriple = Triple(M.getTargetTriple()); }
+  ModuleMemProfiler(Module &M) { TargetTriple = M.getTargetTriple(); }
 
   bool instrumentModule(Module &);
 
@@ -426,7 +426,7 @@ MemProfiler::isInterestingMemoryAccess(Instruction *I) const {
     if (GV->hasSection()) {
       StringRef SectionName = GV->getSection();
       // Check if the global is in the PGO counters section.
-      auto OF = Triple(I->getModule()->getTargetTriple()).getObjectFormat();
+      auto OF = I->getModule()->getTargetTriple().getObjectFormat();
       if (SectionName.ends_with(
               getInstrProfSectionName(IPSK_cnts, OF, /*AddSegmentInfo=*/false)))
         return std::nullopt;
@@ -542,7 +542,7 @@ void createProfileFileNameVar(Module &M) {
   GlobalVariable *ProfileNameVar = new GlobalVariable(
       M, ProfileNameConst->getType(), /*isConstant=*/true,
       GlobalValue::WeakAnyLinkage, ProfileNameConst, MemProfFilenameVar);
-  Triple TT(M.getTargetTriple());
+  const Triple &TT = M.getTargetTriple();
   if (TT.supportsCOMDAT()) {
     ProfileNameVar->setLinkage(GlobalValue::ExternalLinkage);
     ProfileNameVar->setComdat(M.getOrInsertComdat(MemProfFilenameVar));
@@ -557,7 +557,7 @@ void createMemprofHistogramFlagVar(Module &M) {
   auto MemprofHistogramFlag = new GlobalVariable(
       M, IntTy1, true, GlobalValue::WeakAnyLinkage,
       Constant::getIntegerValue(IntTy1, APInt(1, ClHistogram)), VarName);
-  Triple TT(M.getTargetTriple());
+  const Triple &TT = M.getTargetTriple();
   if (TT.supportsCOMDAT()) {
     MemprofHistogramFlag->setLinkage(GlobalValue::ExternalLinkage);
     MemprofHistogramFlag->setComdat(M.getOrInsertComdat(VarName));
@@ -571,7 +571,7 @@ void createMemprofDefaultOptionsVar(Module &M) {
   GlobalVariable *OptionsVar = new GlobalVariable(
       M, OptionsConst->getType(), /*isConstant=*/true,
       GlobalValue::WeakAnyLinkage, OptionsConst, getMemprofOptionsSymbolName());
-  Triple TT(M.getTargetTriple());
+  const Triple &TT = M.getTargetTriple();
   if (TT.supportsCOMDAT()) {
     OptionsVar->setLinkage(GlobalValue::ExternalLinkage);
     OptionsVar->setComdat(M.getOrInsertComdat(OptionsVar->getName()));
diff --git a/llvm/lib/Transforms/Instrumentation/MemorySanitizer.cpp b/llvm/lib/Transforms/Instrumentation/MemorySanitizer.cpp
index 52e42932fc751..ba925275faba6 100644
--- a/llvm/lib/Transforms/Instrumentation/MemorySanitizer.cpp
+++ b/llvm/lib/Transforms/Instrumentation/MemorySanitizer.cpp
@@ -994,7 +994,7 @@ FunctionCallee MemorySanitizer::getKmsanShadowOriginAccessFn(bool isStore,
 void MemorySanitizer::initializeModule(Module &M) {
   auto &DL = M.getDataLayout();
 
-  TargetTriple = Triple(M.getTargetTriple());
+  TargetTriple = M.getTargetTriple();
 
   bool ShadowPassed = ClShadowBase.getNumOccurrences() > 0;
   bool OriginPassed = ClOriginBase.getNumOccurrences() > 0;
diff --git a/llvm/lib/Transforms/Instrumentation/SanitizerBinaryMetadata.cpp b/llvm/lib/Transforms/Instrumentation/SanitizerBinaryMetadata.cpp
index 9ebc235f58142..66a9f7c43d3fe 100644
--- a/llvm/lib/Transforms/Instrumentation/SanitizerBinaryMetadata.cpp
+++ b/llvm/lib/Transforms/Instrumentation/SanitizerBinaryMetadata.cpp
@@ -374,7 +374,7 @@ bool SanitizerBinaryMetadata::pretendAtomicAccess(const Value *Addr) {
   // Some compiler-generated accesses are known racy, to avoid false positives
   // in data-race analysis pretend they're atomic.
   if (GV->hasSection()) {
-    const auto OF = Triple(Mod.getTargetTriple()).getObjectFormat();
+    const auto OF = Mod.getTargetTriple().getObjectFormat();
     const auto ProfSec =
         getInstrProfSectionName(IPSK_cnts, OF, /*AddSegmentInfo=*/false);
     if (GV->getSection().ends_with(ProfSec))
diff --git a/llvm/lib/Transforms/Instrumentation/SanitizerCoverage.cpp b/llvm/lib/Transforms/Instrumentation/SanitizerCoverage.cpp
index ac033d92e30d8..398f83e3b3462 100644
--- a/llvm/lib/Transforms/Instrumentation/SanitizerCoverage.cpp
+++ b/llvm/lib/Transforms/Instrumentation/SanitizerCoverage.cpp
@@ -400,7 +400,7 @@ bool ModuleSanitizerCoverage::instrumentModule() {
   DL = &M.getDataLayout();
   CurModule = &M;
   CurModuleUniqueId = getUniqueModuleId(CurModule);
-  TargetTriple = Triple(M.getTargetTriple());
+  TargetTriple = M.getTargetTriple();
   FunctionGuardArray = nullptr;
   Function8bitCounterArray = nullptr;
   FunctionBoolArray = nullptr;
diff --git a/llvm/lib/Transforms/Instrumentation/ThreadSanitizer.cpp b/llvm/lib/Transforms/Instrumentation/ThreadSanitizer.cpp
index 57e7667150b99..2b403b695c1d2 100644
--- a/llvm/lib/Transforms/Instrumentation/ThreadSanitizer.cpp
+++ b/llvm/lib/Transforms/Instrumentation/ThreadSanitizer.cpp
@@ -360,7 +360,7 @@ static bool shouldInstrumentReadWriteFromAddress(const Module *M, Value *Addr) {
     if (GV->hasSection()) {
       StringRef SectionName = GV->getSection();
       // Check if the global is in the PGO counters section.
-      auto OF = Triple(M->getTargetTriple()).getObjectFormat();
+      auto OF = M->getTargetTriple().getObjectFormat();
       if (SectionName.ends_with(
               getInstrProfSectionName(IPSK_cnts, OF, /*AddSegmentInfo=*/false)))
         return false;
diff --git a/llvm/lib/Transforms/Instrumentation/TypeSanitizer.cpp b/llvm/lib/Transforms/Instrumentation/TypeSanitizer.cpp
index 8c28a8e764462..83b66299deb1a 100644
--- a/llvm/lib/Transforms/Instrumentation/TypeSanitizer.cpp
+++ b/llvm/lib/Transforms/Instrumentation/TypeSanitizer.cpp
@@ -121,7 +121,7 @@ struct TypeSanitizer {
 } // namespace
 
 TypeSanitizer::TypeSanitizer(Module &M)
-    : TargetTriple(Triple(M.getTargetTriple())),
+    : TargetTriple(M.getTargetTriple()),
       AnonNameRegex("^_ZTS.*N[1-9][0-9]*_GLOBAL__N") {
   const DataLayout &DL = M.getDataLayout();
   IntptrTy = DL.getIntPtrType(M.getContext());
diff --git a/llvm/tools/bugpoint/BugDriver.cpp b/llvm/tools/bugpoint/BugDriver.cpp
index f9b8d09501672..ecd9f9da780b0 100644
--- a/llvm/tools/bugpoint/BugDriver.cpp
+++ b/llvm/tools/bugpoint/BugDriver.cpp
@@ -114,7 +114,8 @@ std::unique_ptr<Module> llvm::parseInputFile(StringRef Filename,
     TargetTriple.setTriple(TheTriple.getTriple());
   }
 
-  Result->setTargetTriple(TargetTriple.getTriple()); // override the triple
+  // override the triple
+  Result->setTargetTriple(Triple(TargetTriple.getTriple()));
   return Result;
 }
 
diff --git a/llvm/tools/llc/llc.cpp b/llvm/tools/llc/llc.cpp
index 3694ff79b5436..456d5f8f2a2f8 100644
--- a/llvm/tools/llc/llc.cpp
+++ b/llvm/tools/llc/llc.cpp
@@ -575,7 +575,7 @@ static int compileModule(char **argv, LLVMContext &Context) {
       return 1;
     }
     if (!TargetTriple.empty())
-      M->setTargetTriple(Triple::normalize(TargetTriple));
+      M->setTargetTriple(Triple(Triple::normalize(TargetTriple)));
 
     std::optional<CodeModel::Model> CM_IR = M->getCodeModel();
     if (!CM && CM_IR)
@@ -633,7 +633,7 @@ static int compileModule(char **argv, LLVMContext &Context) {
   }
 
   // Add an appropriate TargetLibraryInfo pass for the module's triple.
-  TargetLibraryInfoImpl TLII(Triple(M->getTargetTriple()));
+  TargetLibraryInfoImpl TLII(M->getTargetTriple());
 
   // The -disable-simplify-libcalls flag actually disables all builtin optzns.
   if (DisableSimplifyLibCalls)
diff --git a/llvm/tools/lli/lli.cpp b/llvm/tools/lli/lli.cpp
index 19246f0394167..7b9f997ea9a5e 100644
--- a/llvm/tools/lli/lli.cpp
+++ b/llvm/tools/lli/lli.cpp
@@ -373,13 +373,12 @@ class LLIObjectCache : public ObjectCache {
 // currently handle external linking) we add a secondary module which defines
 // an empty '__main' function.
 static void addCygMingExtraModule(ExecutionEngine &EE, LLVMContext &Context,
-                                  StringRef TargetTripleStr) {
+                                  const Triple &TargetTriple) {
   IRBuilder<> Builder(Context);
-  Triple TargetTriple(TargetTripleStr);
 
   // Create a new module.
   std::unique_ptr<Module> M = std::make_unique<Module>("CygMingHelper", Context);
-  M->setTargetTriple(TargetTripleStr);
+  M->setTargetTriple(TargetTriple);
 
   // Create an empty function named "__main".
   Type *ReturnTy;
@@ -492,7 +491,7 @@ int main(int argc, char **argv, char * const *envp) {
 
   // If we are supposed to override the target triple, do so now.
   if (!TargetTriple.empty())
-    Mod->setTargetTriple(Triple::normalize(TargetTriple));
+    Mod->setTargetTriple(Triple(Triple::normalize(TargetTriple)));
 
   // Enable MCJIT if desired.
   RTDyldMemoryManager *RTDyldMM = nullptr;
@@ -588,7 +587,7 @@ int main(int argc, char **argv, char * const *envp) {
 
   // If the target is Cygwin/MingW and we are generating remote code, we
   // need an extra module to help out with linking.
-  if (RemoteMCJIT && Triple(Mod->getTargetTriple()).isOSCygMing()) {
+  if (RemoteMCJIT && Mod->getTargetTriple().isOSCygMing()) {
     addCygMingExtraModule(*EE, Context, Mod->getTargetTriple());
   }
 
@@ -932,7 +931,7 @@ int runOrcJIT(const char *ProgName) {
   std::optional<DataLayout> DL;
   MainModule.withModuleDo([&](Module &M) {
       if (!M.getTargetTriple().empty())
-        TT = Triple(M.getTargetTriple());
+        TT = M.getTargetTriple();
       if (!M.getDataLayout().isDefault())
         DL = M.getDataLayout();
     });
diff --git a/llvm/tools/llvm-exegesis/lib/Assembler.cpp b/llvm/tools/llvm-exegesis/lib/Assembler.cpp
index 1e97cd24fe099..b6104d10af3ca 100644
--- a/llvm/tools/llvm-exegesis/lib/Assembler.cpp
+++ b/llvm/tools/llvm-exegesis/lib/Assembler.cpp
@@ -310,7 +310,7 @@ Error assembleToStream(const ExegesisTarget &ET,
   MCContext &MCContext = MMIWP->getMMI().getContext();
   legacy::PassManager PM;
 
-  TargetLibraryInfoImpl TLII(Triple(Module->getTargetTriple()));
+  TargetLibraryInfoImpl TLII(Module->getTargetTriple());
   PM.add(new TargetLibraryInfoWrapperPass(TLII));
 
   TargetPassConfig *TPC = TM->createPassConfig(PM);
diff --git a/llvm/tools/llvm-isel-fuzzer/llvm-isel-fuzzer.cpp b/llvm/tools/llvm-isel-fuzzer/llvm-isel-fuzzer.cpp
index cc7d0869da05e..8d5e00b562539 100644
--- a/llvm/tools/llvm-isel-fuzzer/llvm-isel-fuzzer.cpp
+++ b/llvm/tools/llvm-isel-fuzzer/llvm-isel-fuzzer.cpp
@@ -91,7 +91,7 @@ extern "C" int LLVMFuzzerTestOneInput(const uint8_t *Data, size_t Size) {
   }
 
   // Set up the module to build for our target.
-  M->setTargetTriple(TM->getTargetTriple().normalize());
+  M->setTargetTriple(Triple(TM->getTargetTriple().normalize()));
   M->setDataLayout(TM->createDataLayout());
 
   // Build up a PM to do instruction selection.
diff --git a/llvm/tools/llvm-opt-fuzzer/llvm-opt-fuzzer.cpp b/llvm/tools/llvm-opt-fuzzer/llvm-opt-fuzzer.cpp
index a4af4b4a118fd..ef10e50e6d1f0 100644
--- a/llvm/tools/llvm-opt-fuzzer/llvm-opt-fuzzer.cpp
+++ b/llvm/tools/llvm-opt-fuzzer/llvm-opt-fuzzer.cpp
@@ -124,7 +124,7 @@ extern "C" int LLVMFuzzerTestOneInput(const uint8_t *Data, size_t Size) {
   // Set up target dependant options
   //
 
-  M->setTargetTriple(TM->getTargetTriple().normalize());
+  M->setTargetTriple(Triple(TM->getTargetTriple().normalize()));
   M->setDataLayout(TM->createDataLayout());
   codegen::setFunctionAttributes(TM->getTargetCPU(),
                                  TM->getTargetFeatureString(), *M);
diff --git a/llvm/tools/lto/lto.cpp b/llvm/tools/lto/lto.cpp
index c8fbbd1e0b24b..b377693444189 100644
--- a/llvm/tools/lto/lto.cpp
+++ b/llvm/tools/lto/lto.cpp
@@ -302,11 +302,11 @@ lto_module_t lto_module_create_in_codegen_context(const void *mem,
 void lto_module_dispose(lto_module_t mod) { delete unwrap(mod); }
 
 const char* lto_module_get_target_triple(lto_module_t mod) {
-  return unwrap(mod)->getTargetTriple().c_str();
+  return unwrap(mod)->getTargetTriple().str().c_str();
 }
 
 void lto_module_set_target_triple(lto_module_t mod, const char *triple) {
-  return unwrap(mod)->setTargetTriple(StringRef(triple));
+  return unwrap(mod)->setTargetTriple(Triple(StringRef(triple)));
 }
 
 unsigned int lto_module_get_num_symbols(lto_module_t mod) {
diff --git a/llvm/tools/opt/optdriver.cpp b/llvm/tools/opt/optdriver.cpp
index 8ef249e1708b9..4759d03ba80d7 100644
--- a/llvm/tools/opt/optdriver.cpp
+++ b/llvm/tools/opt/optdriver.cpp
@@ -577,7 +577,7 @@ extern "C" int optMain(
 
   // If we are supposed to override the target triple, do so now.
   if (!TargetTriple.empty())
-    M->setTargetTriple(Triple::normalize(TargetTriple));
+    M->setTargetTriple(Triple(Triple::normalize(TargetTriple)));
 
   // Immediately run the verifier to catch any problems before starting up the
   // pass pipelines.  Otherwise we can crash on broken code during
diff --git a/llvm/unittests/Analysis/LazyCallGraphTest.cpp b/llvm/unittests/Analysis/LazyCallGraphTest.cpp
index 6ca233a50f31f..49677d7301f88 100644
--- a/llvm/unittests/Analysis/LazyCallGraphTest.cpp
+++ b/llvm/unittests/Analysis/LazyCallGraphTest.cpp
@@ -218,7 +218,7 @@ static const char DiamondOfTrianglesRefGraph[] =
      "}\n";
 
 static LazyCallGraph buildCG(Module &M) {
-  TargetLibraryInfoImpl TLII(Triple(M.getTargetTriple()));
+  TargetLibraryInfoImpl TLII(M.getTargetTriple());
   TargetLibraryInfo TLI(TLII);
   auto GetTLI = [&TLI](Function &F) -> TargetLibraryInfo & { return TLI; };
 
diff --git a/llvm/unittests/ExecutionEngine/MCJIT/MCJITTestBase.h b/llvm/unittests/ExecutionEngine/MCJIT/MCJITTestBase.h
index cfd5416585d12..a7cd47325845a 100644
--- a/llvm/unittests/ExecutionEngine/MCJIT/MCJITTestBase.h
+++ b/llvm/unittests/ExecutionEngine/MCJIT/MCJITTestBase.h
@@ -40,7 +40,7 @@ class TrivialModuleBuilder {
 
   Module *createEmptyModule(StringRef Name = StringRef()) {
     Module * M = new Module(Name, Context);
-    M->setTargetTriple(Triple::normalize(BuilderTriple));
+    M->setTargetTriple(Triple(Triple::normalize(BuilderTriple)));
     return M;
   }
 
diff --git a/llvm/unittests/ExecutionEngine/Orc/OrcTestCommon.cpp b/llvm/unittests/ExecutionEngine/Orc/OrcTestCommon.cpp
index 307f14dfe24d0..aaa39f915c085 100644
--- a/llvm/unittests/ExecutionEngine/Orc/OrcTestCommon.cpp
+++ b/llvm/unittests/ExecutionEngine/Orc/OrcTestCommon.cpp
@@ -16,11 +16,11 @@ using namespace llvm;
 
 bool OrcNativeTarget::NativeTargetInitialized = false;
 
-ModuleBuilder::ModuleBuilder(LLVMContext &Context, StringRef Triple,
+ModuleBuilder::ModuleBuilder(LLVMContext &Context, StringRef TripleStr,
                              StringRef Name)
-  : M(new Module(Name, Context)) {
-  if (Triple != "")
-    M->setTargetTriple(Triple);
+    : M(new Module(Name, Context)) {
+  if (TripleStr != "")
+    M->setTargetTriple(Triple(TripleStr));
 }
 
 void llvm::orc::CoreAPIsBasedStandardTest::OverridableDispatcher::dispatch(
diff --git a/llvm/unittests/ExecutionEngine/Orc/RTDyldObjectLinkingLayerTest.cpp b/llvm/unittests/ExecutionEngine/Orc/RTDyldObjectLinkingLayerTest.cpp
index 82d6968ea9874..ed1feed6a5a9e 100644
--- a/llvm/unittests/ExecutionEngine/Orc/RTDyldObjectLinkingLayerTest.cpp
+++ b/llvm/unittests/ExecutionEngine/Orc/RTDyldObjectLinkingLayerTest.cpp
@@ -73,7 +73,7 @@ static bool testSetProcessAllSections(std::unique_ptr<MemoryBuffer> Obj,
 TEST(RTDyldObjectLinkingLayerTest, TestSetProcessAllSections) {
   LLVMContext Context;
   auto M = std::make_unique<Module>("", Context);
-  M->setTargetTriple("x86_64-unknown-linux-gnu");
+  M->setTargetTriple(Triple("x86_64-unknown-linux-gnu"));
 
   // These values are only here to ensure that the module is non-empty.
   // They are no longer relevant to the test.
@@ -88,7 +88,7 @@ TEST(RTDyldObjectLinkingLayerTest, TestSetProcessAllSections) {
   // to try to build a TM.
   OrcNativeTarget::initialize();
   std::unique_ptr<TargetMachine> TM(EngineBuilder().selectTarget(
-      Triple(M->getTargetTriple()), "", "", SmallVector<std::string, 1>()));
+      M->getTargetTriple(), "", "", SmallVector<std::string, 1>()));
   if (!TM)
     GTEST_SKIP();
 
diff --git a/llvm/unittests/ExecutionEngine/Orc/ReOptimizeLayerTest.cpp b/llvm/unittests/ExecutionEngine/Orc/ReOptimizeLayerTest.cpp
index 991b12def55fa..78dc0f24c0f99 100644
--- a/llvm/unittests/ExecutionEngine/Orc/ReOptimizeLayerTest.cpp
+++ b/llvm/unittests/ExecutionEngine/Orc/ReOptimizeLayerTest.cpp
@@ -165,7 +165,7 @@ TEST_F(ReOptimizeLayerTest, BasicReOptimization) {
 
   ThreadSafeContext Ctx(std::make_unique<LLVMContext>());
   auto M = std::make_unique<Module>("<main>", *Ctx.getContext());
-  M->setTargetTriple(sys::getProcessTriple());
+  M->setTargetTriple(Triple(sys::getProcessTriple()));
 
   (void)createRetFunction(M.get(), "main", 42);
 
diff --git a/llvm/unittests/IR/LegacyPassManagerTest.cpp b/llvm/unittests/IR/LegacyPassManagerTest.cpp
index d7b58518fa4b8..71241e44831e0 100644
--- a/llvm/unittests/IR/LegacyPassManagerTest.cpp
+++ b/llvm/unittests/IR/LegacyPassManagerTest.cpp
@@ -425,7 +425,7 @@ namespace llvm {
       mod->setDataLayout("e-p:64:64:64-i1:8:8-i8:8:8-i16:16:16-i32:32:32-"
                          "i64:64:64-f32:32:32-f64:64:64-v64:64:64-v128:128:128-"
                          "a:0:64-s:64:64-f80:128:128");
-      mod->setTargetTriple("x86_64-unknown-linux-gnu");
+      mod->setTargetTriple(Triple("x86_64-unknown-linux-gnu"));
 
       // Type Definitions
       std::vector<Type*>FuncTy_0_args;
diff --git a/llvm/unittests/Target/AArch64/InstSizes.cpp b/llvm/unittests/Target/AArch64/InstSizes.cpp
index 87619dbc34851..fc21fbdd2d5d4 100644
--- a/llvm/unittests/Target/AArch64/InstSizes.cpp
+++ b/llvm/unittests/Target/AArch64/InstSizes.cpp
@@ -71,7 +71,7 @@ void runChecks(
   std::unique_ptr<Module> M = MParser->parseIRModule();
   ASSERT_TRUE(M);
 
-  M->setTargetTriple(TM->getTargetTriple().getTriple());
+  M->setTargetTriple(TM->getTargetTriple());
   M->setDataLayout(TM->createDataLayout());
 
   MachineModuleInfo MMI(TM);
diff --git a/llvm/unittests/Target/ARM/InstSizes.cpp b/llvm/unittests/Target/ARM/InstSizes.cpp
index 8b743f155dee6..56ebfed11bdcd 100644
--- a/llvm/unittests/Target/ARM/InstSizes.cpp
+++ b/llvm/unittests/Target/ARM/InstSizes.cpp
@@ -52,7 +52,7 @@ void runChecks(
   std::unique_ptr<Module> M = MParser->parseIRModule();
   ASSERT_TRUE(M);
 
-  M->setTargetTriple(TM->getTargetTriple().getTriple());
+  M->setTargetTriple(TM->getTargetTriple());
   M->setDataLayout(TM->createDataLayout());
 
   MachineModuleInfo MMI(TM);
diff --git a/llvm/unittests/Target/LoongArch/InstSizes.cpp b/llvm/unittests/Target/LoongArch/InstSizes.cpp
index 4a679707fc0f1..cff0eb6c04ca4 100644
--- a/llvm/unittests/Target/LoongArch/InstSizes.cpp
+++ b/llvm/unittests/Target/LoongArch/InstSizes.cpp
@@ -70,7 +70,7 @@ void runChecks(
   std::unique_ptr<Module> M = MParser->parseIRModule();
   ASSERT_TRUE(M);
 
-  M->setTargetTriple(TM->getTargetTriple().getTriple());
+  M->setTargetTriple(TM->getTargetTriple());
   M->setDataLayout(TM->createDataLayout());
 
   MachineModuleInfo MMI(TM);
diff --git a/llvm/unittests/Target/X86/MachineSizeOptsTest.cpp b/llvm/unittests/Target/X86/MachineSizeOptsTest.cpp
index d7f430b629460..f18df9d02db02 100644
--- a/llvm/unittests/Target/X86/MachineSizeOptsTest.cpp
+++ b/llvm/unittests/Target/X86/MachineSizeOptsTest.cpp
@@ -75,7 +75,7 @@ class MachineSizeOptsTest : public testing::Test {
     M = Parser->parseIRModule();
     if (!M)
       report_fatal_error("parseIRModule failed");
-    M->setTargetTriple(TM->getTargetTriple().getTriple());
+    M->setTargetTriple(TM->getTargetTriple());
     M->setDataLayout(TM->createDataLayout());
     MMI = std::make_unique<MachineModuleInfo>(TM.get());
     if (Parser->parseMachineFunctions(*M, *MMI))
diff --git a/llvm/unittests/Transforms/Vectorize/VPlanHCFGTest.cpp b/llvm/unittests/Transforms/Vectorize/VPlanHCFGTest.cpp
index 508bee2051918..46554a8938af1 100644
--- a/llvm/unittests/Transforms/Vectorize/VPlanHCFGTest.cpp
+++ b/llvm/unittests/Transforms/Vectorize/VPlanHCFGTest.cpp
@@ -171,7 +171,7 @@ compound=true
 )";
   EXPECT_EQ(ExpectedStr, FullDump);
 #endif
-  TargetLibraryInfoImpl TLII(Triple(M.getTargetTriple()));
+  TargetLibraryInfoImpl TLII(M.getTargetTriple());
   TargetLibraryInfo TLI(TLII);
   VPlanTransforms::VPInstructionsToVPRecipes(
       Plan, [](PHINode *P) { return nullptr; }, *SE, TLI);
@@ -201,7 +201,7 @@ TEST_F(VPlanHCFGTest, testVPInstructionToVPRecipesInner) {
   BasicBlock *LoopHeader = F->getEntryBlock().getSingleSuccessor();
   auto Plan = buildVPlan(LoopHeader);
 
-  TargetLibraryInfoImpl TLII(Triple(M.getTargetTriple()));
+  TargetLibraryInfoImpl TLII(M.getTargetTriple());
   TargetLibraryInfo TLI(TLII);
   VPlanTransforms::VPInstructionsToVPRecipes(
       Plan, [](PHINode *P) { return nullptr; }, *SE, TLI);
diff --git a/offload/plugins-nextgen/common/src/PluginInterface.cpp b/offload/plugins-nextgen/common/src/PluginInterface.cpp
index bb3fc77258f3e..4d2ebcbc7be8e 100644
--- a/offload/plugins-nextgen/common/src/PluginInterface.cpp
+++ b/offload/plugins-nextgen/common/src/PluginInterface.cpp
@@ -1711,7 +1711,7 @@ Expected<bool> GenericPluginTy::checkBitcodeImage(StringRef Image) const {
     return ModuleOrErr.takeError();
   Module &M = **ModuleOrErr;
 
-  return Triple(M.getTargetTriple()).getArch() == getTripleArch();
+  return M.getTargetTriple().getArch() == getTripleArch();
 }
 
 int32_t GenericPluginTy::is_initialized() const { return Initialized; }
diff --git a/polly/lib/CodeGen/IslNodeBuilder.cpp b/polly/lib/CodeGen/IslNodeBuilder.cpp
index 40205215ea0b3..6affc202d0a4c 100644
--- a/polly/lib/CodeGen/IslNodeBuilder.cpp
+++ b/polly/lib/CodeGen/IslNodeBuilder.cpp
@@ -600,8 +600,7 @@ void IslNodeBuilder::createForParallel(__isl_take isl_ast_node *For) {
   // derived class determined by TargetMachine, AssumptionCache can be
   // configured using a TargetTransformInfo object also derived from
   // TargetMachine.
-  TargetLibraryInfoImpl BaselineInfoImpl(
-      Triple(SubFn->getParent()->getTargetTriple()));
+  TargetLibraryInfoImpl BaselineInfoImpl(SubFn->getParent()->getTargetTriple());
   TargetLibraryInfo CalleeTLI(BaselineInfoImpl, SubFn);
   AssumptionCache CalleeAC(*SubFn);
   std::unique_ptr<ScalarEvolution> SubSE = std::make_unique<ScalarEvolution>(
diff --git a/polly/lib/CodeGen/PerfMonitor.cpp b/polly/lib/CodeGen/PerfMonitor.cpp
index 1a79161468544..4c1eab0050848 100644
--- a/polly/lib/CodeGen/PerfMonitor.cpp
+++ b/polly/lib/CodeGen/PerfMonitor.cpp
@@ -64,7 +64,7 @@ Function *PerfMonitor::getRDTSCP() {
 
 PerfMonitor::PerfMonitor(const Scop &S, Module *M)
     : M(M), Builder(M->getContext()), S(S) {
-  if (Triple(M->getTargetTriple()).getArch() == llvm::Triple::x86_64)
+  if (M->getTargetTriple().getArch() == llvm::Triple::x86_64)
     Supported = true;
   else
     Supported = false;

>From 3af1d865c5398434270e6e4366e8f33308b94086 Mon Sep 17 00:00:00 2001
From: Nikita Popov <npopov at redhat.com>
Date: Wed, 5 Mar 2025 14:37:29 +0100
Subject: [PATCH 2/4] Fix mlir, address review comments

---
 llvm/include/llvm/IR/Module.h                    |  2 +-
 llvm/lib/Analysis/Lint.cpp                       |  6 +++---
 llvm/lib/IR/Verifier.cpp                         |  6 +++---
 llvm/lib/LTO/LTOModule.cpp                       | 13 ++++++-------
 llvm/lib/Target/SPIRV/SPIRVAPI.cpp               |  2 +-
 llvm/tools/bugpoint/BugDriver.cpp                |  2 +-
 llvm/tools/llvm-isel-fuzzer/llvm-isel-fuzzer.cpp |  2 +-
 llvm/tools/llvm-opt-fuzzer/llvm-opt-fuzzer.cpp   |  2 +-
 mlir/lib/ExecutionEngine/ExecutionEngine.cpp     |  4 ++--
 mlir/lib/Target/LLVM/ModuleToObject.cpp          |  2 +-
 mlir/lib/Target/LLVMIR/ModuleImport.cpp          |  5 +++--
 mlir/lib/Target/LLVMIR/ModuleTranslation.cpp     |  3 ++-
 12 files changed, 25 insertions(+), 24 deletions(-)

diff --git a/llvm/include/llvm/IR/Module.h b/llvm/include/llvm/IR/Module.h
index 48dc29c24c582..2fd2d6887022c 100644
--- a/llvm/include/llvm/IR/Module.h
+++ b/llvm/include/llvm/IR/Module.h
@@ -191,7 +191,7 @@ class LLVM_ABI Module {
   std::string SourceFileName;     ///< Original source file name for module,
                                   ///< recorded in bitcode.
   /// Platform target triple Module compiled on
-  /// Format: (arch)(sub)-(vendor)-(sys0-(abi)
+  /// Format: (arch)(sub)-(vendor)-(sys)-(abi)
   // FIXME: Default construction is not the same as empty triple :(
   Triple TargetTriple = Triple("");
   NamedMDSymTabType NamedMDSymTab;  ///< NamedMDNode names.
diff --git a/llvm/lib/Analysis/Lint.cpp b/llvm/lib/Analysis/Lint.cpp
index 1db0ca372d797..a01672844e0ec 100644
--- a/llvm/lib/Analysis/Lint.cpp
+++ b/llvm/lib/Analysis/Lint.cpp
@@ -127,7 +127,7 @@ class Lint : public InstVisitor<Lint> {
 
 public:
   Module *Mod;
-  Triple TT;
+  const Triple &TT;
   const DataLayout *DL;
   AliasAnalysis *AA;
   AssumptionCache *AC;
@@ -139,8 +139,8 @@ class Lint : public InstVisitor<Lint> {
 
   Lint(Module *Mod, const DataLayout *DL, AliasAnalysis *AA,
        AssumptionCache *AC, DominatorTree *DT, TargetLibraryInfo *TLI)
-      : Mod(Mod), TT(Mod->getTargetTriple().normalize()), DL(DL), AA(AA),
-        AC(AC), DT(DT), TLI(TLI), MessagesStr(Messages) {}
+      : Mod(Mod), TT(Mod->getTargetTriple()), DL(DL), AA(AA), AC(AC), DT(DT),
+        TLI(TLI), MessagesStr(Messages) {}
 
   void WriteValues(ArrayRef<const Value *> Vs) {
     for (const Value *V : Vs) {
diff --git a/llvm/lib/IR/Verifier.cpp b/llvm/lib/IR/Verifier.cpp
index e839761f47f1f..524e9647bfd35 100644
--- a/llvm/lib/IR/Verifier.cpp
+++ b/llvm/lib/IR/Verifier.cpp
@@ -141,7 +141,7 @@ struct VerifierSupport {
   raw_ostream *OS;
   const Module &M;
   ModuleSlotTracker MST;
-  Triple TT;
+  const Triple &TT;
   const DataLayout &DL;
   LLVMContext &Context;
 
@@ -153,8 +153,8 @@ struct VerifierSupport {
   bool TreatBrokenDebugInfoAsError = true;
 
   explicit VerifierSupport(raw_ostream *OS, const Module &M)
-      : OS(OS), M(M), MST(&M), TT(M.getTargetTriple().normalize()),
-        DL(M.getDataLayout()), Context(M.getContext()) {}
+      : OS(OS), M(M), MST(&M), TT(M.getTargetTriple()), DL(M.getDataLayout()),
+        Context(M.getContext()) {}
 
 private:
   void Write(const Module *M) {
diff --git a/llvm/lib/LTO/LTOModule.cpp b/llvm/lib/LTO/LTOModule.cpp
index 751615e47631a..84d6c0822b797 100644
--- a/llvm/lib/LTO/LTOModule.cpp
+++ b/llvm/lib/LTO/LTOModule.cpp
@@ -200,14 +200,13 @@ LTOModule::makeLTOModule(MemoryBufferRef Buffer, const TargetOptions &options,
     return EC;
   std::unique_ptr<Module> &M = *MOrErr;
 
-  std::string TripleStr = M->getTargetTriple().str();
-  if (TripleStr.empty())
-    TripleStr = sys::getDefaultTargetTriple();
-  llvm::Triple Triple(TripleStr);
+  llvm::Triple Triple = M->getTargetTriple();
+  if (Triple.empty())
+    Triple = llvm::Triple(sys::getDefaultTargetTriple());
 
   // find machine architecture for this module
   std::string errMsg;
-  const Target *march = TargetRegistry::lookupTarget(TripleStr, errMsg);
+  const Target *march = TargetRegistry::lookupTarget(Triple.str(), errMsg);
   if (!march)
     return make_error_code(object::object_error::arch_not_found);
 
@@ -229,8 +228,8 @@ LTOModule::makeLTOModule(MemoryBufferRef Buffer, const TargetOptions &options,
       CPU = "cyclone";
   }
 
-  TargetMachine *target = march->createTargetMachine(TripleStr, CPU, FeatureStr,
-                                                     options, std::nullopt);
+  TargetMachine *target = march->createTargetMachine(
+      Triple.str(), CPU, FeatureStr, options, std::nullopt);
 
   std::unique_ptr<LTOModule> Ret(new LTOModule(std::move(M), Buffer, target));
   Ret->parseSymbols();
diff --git a/llvm/lib/Target/SPIRV/SPIRVAPI.cpp b/llvm/lib/Target/SPIRV/SPIRVAPI.cpp
index 759a403a804c7..052dd296265be 100644
--- a/llvm/lib/Target/SPIRV/SPIRVAPI.cpp
+++ b/llvm/lib/Target/SPIRV/SPIRVAPI.cpp
@@ -79,7 +79,7 @@ SPIRVTranslate(Module *M, std::string &SpirvObj, std::string &ErrMsg,
 
   if (TargetTriple.getTriple().empty()) {
     TargetTriple.setTriple(DefaultTriple);
-    M->setTargetTriple(Triple(DefaultTriple));
+    M->setTargetTriple(TargetTriple);
   }
   const Target *TheTarget =
       TargetRegistry::lookupTarget(DefaultMArch, TargetTriple, ErrMsg);
diff --git a/llvm/tools/bugpoint/BugDriver.cpp b/llvm/tools/bugpoint/BugDriver.cpp
index ecd9f9da780b0..2bdfebe6ceb4f 100644
--- a/llvm/tools/bugpoint/BugDriver.cpp
+++ b/llvm/tools/bugpoint/BugDriver.cpp
@@ -115,7 +115,7 @@ std::unique_ptr<Module> llvm::parseInputFile(StringRef Filename,
   }
 
   // override the triple
-  Result->setTargetTriple(Triple(TargetTriple.getTriple()));
+  Result->setTargetTriple(TargetTriple);
   return Result;
 }
 
diff --git a/llvm/tools/llvm-isel-fuzzer/llvm-isel-fuzzer.cpp b/llvm/tools/llvm-isel-fuzzer/llvm-isel-fuzzer.cpp
index 8d5e00b562539..22d33e13639d8 100644
--- a/llvm/tools/llvm-isel-fuzzer/llvm-isel-fuzzer.cpp
+++ b/llvm/tools/llvm-isel-fuzzer/llvm-isel-fuzzer.cpp
@@ -91,7 +91,7 @@ extern "C" int LLVMFuzzerTestOneInput(const uint8_t *Data, size_t Size) {
   }
 
   // Set up the module to build for our target.
-  M->setTargetTriple(Triple(TM->getTargetTriple().normalize()));
+  M->setTargetTriple(TM->getTargetTriple());
   M->setDataLayout(TM->createDataLayout());
 
   // Build up a PM to do instruction selection.
diff --git a/llvm/tools/llvm-opt-fuzzer/llvm-opt-fuzzer.cpp b/llvm/tools/llvm-opt-fuzzer/llvm-opt-fuzzer.cpp
index ef10e50e6d1f0..3b38e3b6fd1a3 100644
--- a/llvm/tools/llvm-opt-fuzzer/llvm-opt-fuzzer.cpp
+++ b/llvm/tools/llvm-opt-fuzzer/llvm-opt-fuzzer.cpp
@@ -124,7 +124,7 @@ extern "C" int LLVMFuzzerTestOneInput(const uint8_t *Data, size_t Size) {
   // Set up target dependant options
   //
 
-  M->setTargetTriple(Triple(TM->getTargetTriple().normalize()));
+  M->setTargetTriple(TM->getTargetTriple());
   M->setDataLayout(TM->createDataLayout());
   codegen::setFunctionAttributes(TM->getTargetCPU(),
                                  TM->getTargetFeatureString(), *M);
diff --git a/mlir/lib/ExecutionEngine/ExecutionEngine.cpp b/mlir/lib/ExecutionEngine/ExecutionEngine.cpp
index 2ecc80400b3db..c1aa6ae3a3c6a 100644
--- a/mlir/lib/ExecutionEngine/ExecutionEngine.cpp
+++ b/mlir/lib/ExecutionEngine/ExecutionEngine.cpp
@@ -131,7 +131,7 @@ void ExecutionEngine::registerSymbols(
 void ExecutionEngine::setupTargetTripleAndDataLayout(Module *llvmModule,
                                                      llvm::TargetMachine *tm) {
   llvmModule->setDataLayout(tm->createDataLayout());
-  llvmModule->setTargetTriple(tm->getTargetTriple().getTriple());
+  llvmModule->setTargetTriple(tm->getTargetTriple());
 }
 
 static std::string makePackedFunctionName(StringRef name) {
@@ -329,7 +329,7 @@ ExecutionEngine::create(Operation *m, const ExecutionEngineOptions &options,
     // COFF format binaries (Windows) need special handling to deal with
     // exported symbol visibility.
     // cf llvm/lib/ExecutionEngine/Orc/LLJIT.cpp LLJIT::createObjectLinkingLayer
-    llvm::Triple targetTriple(llvm::Twine(llvmModule->getTargetTriple()));
+    const llvm::Triple &targetTriple = llvmModule->getTargetTriple();
     if (targetTriple.isOSBinFormatCOFF()) {
       objectLayer->setOverrideObjectFlagsWithResponsibilityFlags(true);
       objectLayer->setAutoClaimResponsibilityForObjectSymbols(true);
diff --git a/mlir/lib/Target/LLVM/ModuleToObject.cpp b/mlir/lib/Target/LLVM/ModuleToObject.cpp
index 102d149a7bb58..7f90167cd5563 100644
--- a/mlir/lib/Target/LLVM/ModuleToObject.cpp
+++ b/mlir/lib/Target/LLVM/ModuleToObject.cpp
@@ -233,7 +233,7 @@ void ModuleToObject::setDataLayoutAndTriple(llvm::Module &module) {
   if (targetMachine) {
     // Set the data layout and target triple of the module.
     module.setDataLayout((*targetMachine)->createDataLayout());
-    module.setTargetTriple((*targetMachine)->getTargetTriple().getTriple());
+    module.setTargetTriple((*targetMachine)->getTargetTriple());
   }
 }
 
diff --git a/mlir/lib/Target/LLVMIR/ModuleImport.cpp b/mlir/lib/Target/LLVMIR/ModuleImport.cpp
index 7ea82f61fadbb..76ca7f03240c1 100644
--- a/mlir/lib/Target/LLVMIR/ModuleImport.cpp
+++ b/mlir/lib/Target/LLVMIR/ModuleImport.cpp
@@ -673,8 +673,9 @@ LogicalResult ModuleImport::convertDataLayout() {
 }
 
 void ModuleImport::convertTargetTriple() {
-  mlirModule->setAttr(LLVM::LLVMDialect::getTargetTripleAttrName(),
-                      builder.getStringAttr(llvmModule->getTargetTriple()));
+  mlirModule->setAttr(
+      LLVM::LLVMDialect::getTargetTripleAttrName(),
+      builder.getStringAttr(llvmModule->getTargetTriple().str()));
 }
 
 LogicalResult ModuleImport::convertFunctions() {
diff --git a/mlir/lib/Target/LLVMIR/ModuleTranslation.cpp b/mlir/lib/Target/LLVMIR/ModuleTranslation.cpp
index eda6b51ff45ea..2176e4255216c 100644
--- a/mlir/lib/Target/LLVMIR/ModuleTranslation.cpp
+++ b/mlir/lib/Target/LLVMIR/ModuleTranslation.cpp
@@ -2139,7 +2139,8 @@ prepareLLVMModule(Operation *m, llvm::LLVMContext &llvmContext,
   }
   if (auto targetTripleAttr =
           m->getDiscardableAttr(LLVM::LLVMDialect::getTargetTripleAttrName()))
-    llvmModule->setTargetTriple(cast<StringAttr>(targetTripleAttr).getValue());
+    llvmModule->setTargetTriple(
+        llvm::Triple(cast<StringAttr>(targetTripleAttr).getValue()));
 
   return llvmModule;
 }

>From 5b9d68b2b0c7e6a35e32810886cf1a47b0b8b031 Mon Sep 17 00:00:00 2001
From: Nikita Popov <npopov at redhat.com>
Date: Wed, 5 Mar 2025 14:58:35 +0100
Subject: [PATCH 3/4] Add TargetRegistry::lookupTarget() overload accepting
 Triple

---
 clang/lib/CodeGen/ObjectFilePCHContainerWriter.cpp  |  2 +-
 clang/lib/Interpreter/DeviceOffload.cpp             |  2 +-
 .../clang-linker-wrapper/ClangLinkerWrapper.cpp     |  3 +--
 .../Interpreter/InterpreterExtensionsTest.cpp       |  2 +-
 .../Instruction/MIPS/EmulateInstructionMIPS.cpp     |  4 ++--
 .../Instruction/MIPS64/EmulateInstructionMIPS64.cpp |  4 ++--
 llvm/include/llvm/MC/TargetRegistry.h               | 13 ++++++++++++-
 llvm/lib/Bitcode/Writer/BitcodeWriter.cpp           |  2 +-
 .../ExecutionEngine/Orc/JITTargetMachineBuilder.cpp |  2 +-
 llvm/lib/ExecutionEngine/TargetSelect.cpp           |  2 +-
 llvm/lib/LTO/LTOBackend.cpp                         |  3 +--
 llvm/lib/LTO/LTOModule.cpp                          |  2 +-
 llvm/lib/LTO/ThinLTOCodeGenerator.cpp               |  3 +--
 llvm/lib/MC/TargetRegistry.cpp                      | 11 ++++++-----
 llvm/lib/Object/ELFObjectFile.cpp                   |  2 +-
 llvm/lib/Object/ModuleSymbolTable.cpp               |  2 +-
 llvm/tools/llvm-dwarfdump/llvm-dwarfdump.cpp        |  3 +--
 llvm/unittests/DebugInfo/DWARF/DwarfUtils.cpp       |  2 +-
 .../DebugInfo/LogicalView/CodeViewReaderTest.cpp    |  2 +-
 .../DebugInfo/LogicalView/DWARFReaderTest.cpp       |  2 +-
 llvm/unittests/tools/llvm-mca/MCATestBase.cpp       |  2 +-
 21 files changed, 39 insertions(+), 31 deletions(-)

diff --git a/clang/lib/CodeGen/ObjectFilePCHContainerWriter.cpp b/clang/lib/CodeGen/ObjectFilePCHContainerWriter.cpp
index e32778d1b4767..95971e57086e7 100644
--- a/clang/lib/CodeGen/ObjectFilePCHContainerWriter.cpp
+++ b/clang/lib/CodeGen/ObjectFilePCHContainerWriter.cpp
@@ -274,7 +274,7 @@ class PCHContainerGenerator : public ASTConsumer {
     // Ensure the target exists.
     std::string Error;
     auto Triple = Ctx.getTargetInfo().getTriple();
-    if (!llvm::TargetRegistry::lookupTarget(Triple.getTriple(), Error))
+    if (!llvm::TargetRegistry::lookupTarget(Triple, Error))
       llvm::report_fatal_error(llvm::Twine(Error));
 
     // Emit the serialized Clang AST into its own section.
diff --git a/clang/lib/Interpreter/DeviceOffload.cpp b/clang/lib/Interpreter/DeviceOffload.cpp
index 8fb484d185704..5e35fa035b2b8 100644
--- a/clang/lib/Interpreter/DeviceOffload.cpp
+++ b/clang/lib/Interpreter/DeviceOffload.cpp
@@ -77,7 +77,7 @@ llvm::Expected<llvm::StringRef> IncrementalCUDADeviceParser::GeneratePTX() {
   std::string Error;
 
   const llvm::Target *Target = llvm::TargetRegistry::lookupTarget(
-      PTU.TheModule->getTargetTriple().str(), Error);
+      PTU.TheModule->getTargetTriple(), Error);
   if (!Target)
     return llvm::make_error<llvm::StringError>(std::move(Error),
                                                std::error_code());
diff --git a/clang/tools/clang-linker-wrapper/ClangLinkerWrapper.cpp b/clang/tools/clang-linker-wrapper/ClangLinkerWrapper.cpp
index 5f5d103bbcf49..10dfb008cbec2 100644
--- a/clang/tools/clang-linker-wrapper/ClangLinkerWrapper.cpp
+++ b/clang/tools/clang-linker-wrapper/ClangLinkerWrapper.cpp
@@ -622,8 +622,7 @@ Expected<StringRef> writeOffloadFile(const OffloadFile &File) {
 Expected<StringRef> compileModule(Module &M, OffloadKind Kind) {
   llvm::TimeTraceScope TimeScope("Compile module");
   std::string Msg;
-  const Target *T =
-      TargetRegistry::lookupTarget(M.getTargetTriple().str(), Msg);
+  const Target *T = TargetRegistry::lookupTarget(M.getTargetTriple(), Msg);
   if (!T)
     return createStringError(Msg);
 
diff --git a/clang/unittests/Interpreter/InterpreterExtensionsTest.cpp b/clang/unittests/Interpreter/InterpreterExtensionsTest.cpp
index 29af464dbcebb..1c27cfb2c48fa 100644
--- a/clang/unittests/Interpreter/InterpreterExtensionsTest.cpp
+++ b/clang/unittests/Interpreter/InterpreterExtensionsTest.cpp
@@ -61,7 +61,7 @@ class InterpreterExtensionsTest : public InterpreterTestBase {
     TT.setOS(llvm::Triple::UnknownOS);
 
     std::string UnusedErr;
-    return llvm::TargetRegistry::lookupTarget(TT.str(), UnusedErr);
+    return llvm::TargetRegistry::lookupTarget(TT, UnusedErr);
   }
 };
 
diff --git a/lldb/source/Plugins/Instruction/MIPS/EmulateInstructionMIPS.cpp b/lldb/source/Plugins/Instruction/MIPS/EmulateInstructionMIPS.cpp
index 76d7a8272f3fc..f6c8c9de3cd0e 100644
--- a/lldb/source/Plugins/Instruction/MIPS/EmulateInstructionMIPS.cpp
+++ b/lldb/source/Plugins/Instruction/MIPS/EmulateInstructionMIPS.cpp
@@ -67,7 +67,7 @@ EmulateInstructionMIPS::EmulateInstructionMIPS(
   std::string Status;
   llvm::Triple triple = arch.GetTriple();
   const llvm::Target *target =
-      llvm::TargetRegistry::lookupTarget(triple.getTriple(), Status);
+      llvm::TargetRegistry::lookupTarget(triple, Status);
 
 /*
  * If we fail to get the target then we haven't registered it. The
@@ -84,7 +84,7 @@ EmulateInstructionMIPS::EmulateInstructionMIPS(
     LLVMInitializeMipsAsmPrinter();
     LLVMInitializeMipsTargetMC();
     LLVMInitializeMipsDisassembler();
-    target = llvm::TargetRegistry::lookupTarget(triple.getTriple(), Status);
+    target = llvm::TargetRegistry::lookupTarget(triple, Status);
   }
 #endif
 
diff --git a/lldb/source/Plugins/Instruction/MIPS64/EmulateInstructionMIPS64.cpp b/lldb/source/Plugins/Instruction/MIPS64/EmulateInstructionMIPS64.cpp
index e33ca95b523be..7693a27a5ca86 100644
--- a/lldb/source/Plugins/Instruction/MIPS64/EmulateInstructionMIPS64.cpp
+++ b/lldb/source/Plugins/Instruction/MIPS64/EmulateInstructionMIPS64.cpp
@@ -67,7 +67,7 @@ EmulateInstructionMIPS64::EmulateInstructionMIPS64(
   std::string Status;
   llvm::Triple triple = arch.GetTriple();
   const llvm::Target *target =
-      llvm::TargetRegistry::lookupTarget(triple.getTriple(), Status);
+      llvm::TargetRegistry::lookupTarget(triple, Status);
 
 /*
  * If we fail to get the target then we haven't registered it. The
@@ -84,7 +84,7 @@ EmulateInstructionMIPS64::EmulateInstructionMIPS64(
     LLVMInitializeMipsAsmPrinter();
     LLVMInitializeMipsTargetMC();
     LLVMInitializeMipsDisassembler();
-    target = llvm::TargetRegistry::lookupTarget(triple.getTriple(), Status);
+    target = llvm::TargetRegistry::lookupTarget(triple, Status);
   }
 #endif
 
diff --git a/llvm/include/llvm/MC/TargetRegistry.h b/llvm/include/llvm/MC/TargetRegistry.h
index 42d510c17bce3..363fa03f27a70 100644
--- a/llvm/include/llvm/MC/TargetRegistry.h
+++ b/llvm/include/llvm/MC/TargetRegistry.h
@@ -693,12 +693,23 @@ struct TargetRegistry {
 
   static iterator_range<iterator> targets();
 
+  /// lookupTarget - Lookup a target based on a target triple.
+  ///
+  /// \param TripleStr - The triple to use for finding a target.
+  /// \param Error - On failure, an error string describing why no target was
+  /// found.
+  // TODO: Drop this in favor of the method accepting Triple.
+  static const Target *lookupTarget(StringRef TripleStr, std::string &Error) {
+    return lookupTarget(Triple(TripleStr), Error);
+  }
+
   /// lookupTarget - Lookup a target based on a target triple.
   ///
   /// \param Triple - The triple to use for finding a target.
   /// \param Error - On failure, an error string describing why no target was
   /// found.
-  static const Target *lookupTarget(StringRef Triple, std::string &Error);
+  static const Target *lookupTarget(const Triple &TheTriple,
+                                    std::string &Error);
 
   /// lookupTarget - Lookup a target based on an architecture name
   /// and a target triple.  If the architecture name is non-empty,
diff --git a/llvm/lib/Bitcode/Writer/BitcodeWriter.cpp b/llvm/lib/Bitcode/Writer/BitcodeWriter.cpp
index 6e2e45a51069d..a3556af9a683c 100644
--- a/llvm/lib/Bitcode/Writer/BitcodeWriter.cpp
+++ b/llvm/lib/Bitcode/Writer/BitcodeWriter.cpp
@@ -5331,7 +5331,7 @@ void BitcodeWriter::writeSymtab() {
 
     std::string Err;
     const Triple TT(M->getTargetTriple());
-    const Target *T = TargetRegistry::lookupTarget(TT.str(), Err);
+    const Target *T = TargetRegistry::lookupTarget(TT, Err);
     if (!T || !T->hasMCAsmParser())
       return;
   }
diff --git a/llvm/lib/ExecutionEngine/Orc/JITTargetMachineBuilder.cpp b/llvm/lib/ExecutionEngine/Orc/JITTargetMachineBuilder.cpp
index 6dad7124a88e2..5ae1ac6e4250d 100644
--- a/llvm/lib/ExecutionEngine/Orc/JITTargetMachineBuilder.cpp
+++ b/llvm/lib/ExecutionEngine/Orc/JITTargetMachineBuilder.cpp
@@ -39,7 +39,7 @@ Expected<std::unique_ptr<TargetMachine>>
 JITTargetMachineBuilder::createTargetMachine() {
 
   std::string ErrMsg;
-  auto *TheTarget = TargetRegistry::lookupTarget(TT.getTriple(), ErrMsg);
+  auto *TheTarget = TargetRegistry::lookupTarget(TT, ErrMsg);
   if (!TheTarget)
     return make_error<StringError>(std::move(ErrMsg), inconvertibleErrorCode());
 
diff --git a/llvm/lib/ExecutionEngine/TargetSelect.cpp b/llvm/lib/ExecutionEngine/TargetSelect.cpp
index 4fe9494649e7e..4ce031d8dc337 100644
--- a/llvm/lib/ExecutionEngine/TargetSelect.cpp
+++ b/llvm/lib/ExecutionEngine/TargetSelect.cpp
@@ -66,7 +66,7 @@ TargetMachine *EngineBuilder::selectTarget(const Triple &TargetTriple,
       TheTriple.setArch(Type);
   } else {
     std::string Error;
-    TheTarget = TargetRegistry::lookupTarget(TheTriple.getTriple(), Error);
+    TheTarget = TargetRegistry::lookupTarget(TheTriple, Error);
     if (!TheTarget) {
       if (ErrorStr)
         *ErrorStr = Error;
diff --git a/llvm/lib/LTO/LTOBackend.cpp b/llvm/lib/LTO/LTOBackend.cpp
index d9154ecd5d5e5..b38252a3272e8 100644
--- a/llvm/lib/LTO/LTOBackend.cpp
+++ b/llvm/lib/LTO/LTOBackend.cpp
@@ -520,8 +520,7 @@ static Expected<const Target *> initAndLookupTarget(const Config &C,
     Mod.setTargetTriple(Triple(C.DefaultTriple));
 
   std::string Msg;
-  const Target *T =
-      TargetRegistry::lookupTarget(Mod.getTargetTriple().str(), Msg);
+  const Target *T = TargetRegistry::lookupTarget(Mod.getTargetTriple(), Msg);
   if (!T)
     return make_error<StringError>(Msg, inconvertibleErrorCode());
   return T;
diff --git a/llvm/lib/LTO/LTOModule.cpp b/llvm/lib/LTO/LTOModule.cpp
index 84d6c0822b797..7e13646bfa0a8 100644
--- a/llvm/lib/LTO/LTOModule.cpp
+++ b/llvm/lib/LTO/LTOModule.cpp
@@ -206,7 +206,7 @@ LTOModule::makeLTOModule(MemoryBufferRef Buffer, const TargetOptions &options,
 
   // find machine architecture for this module
   std::string errMsg;
-  const Target *march = TargetRegistry::lookupTarget(Triple.str(), errMsg);
+  const Target *march = TargetRegistry::lookupTarget(Triple, errMsg);
   if (!march)
     return make_error_code(object::object_error::arch_not_found);
 
diff --git a/llvm/lib/LTO/ThinLTOCodeGenerator.cpp b/llvm/lib/LTO/ThinLTOCodeGenerator.cpp
index aced35f896027..16326395d0f74 100644
--- a/llvm/lib/LTO/ThinLTOCodeGenerator.cpp
+++ b/llvm/lib/LTO/ThinLTOCodeGenerator.cpp
@@ -577,8 +577,7 @@ void ThinLTOCodeGenerator::crossReferenceSymbol(StringRef Name) {
 // TargetMachine factory
 std::unique_ptr<TargetMachine> TargetMachineBuilder::create() const {
   std::string ErrMsg;
-  const Target *TheTarget =
-      TargetRegistry::lookupTarget(TheTriple.str(), ErrMsg);
+  const Target *TheTarget = TargetRegistry::lookupTarget(TheTriple, ErrMsg);
   if (!TheTarget) {
     report_fatal_error(Twine("Can't load target for this Triple: ") + ErrMsg);
   }
diff --git a/llvm/lib/MC/TargetRegistry.cpp b/llvm/lib/MC/TargetRegistry.cpp
index a9e33c8349bdc..8f253266c4a7c 100644
--- a/llvm/lib/MC/TargetRegistry.cpp
+++ b/llvm/lib/MC/TargetRegistry.cpp
@@ -139,7 +139,7 @@ const Target *TargetRegistry::lookupTarget(StringRef ArchName,
   } else {
     // Get the target specific parser.
     std::string TempError;
-    TheTarget = TargetRegistry::lookupTarget(TheTriple.getTriple(), TempError);
+    TheTarget = TargetRegistry::lookupTarget(TheTriple, TempError);
     if (!TheTarget) {
       Error = "unable to get target for '" + TheTriple.getTriple() +
               "', see --version and --triple.";
@@ -150,19 +150,20 @@ const Target *TargetRegistry::lookupTarget(StringRef ArchName,
   return TheTarget;
 }
 
-const Target *TargetRegistry::lookupTarget(StringRef TT, std::string &Error) {
+const Target *TargetRegistry::lookupTarget(const Triple &TT,
+                                           std::string &Error) {
   // Provide special warning when no targets are initialized.
   if (targets().begin() == targets().end()) {
     Error = "Unable to find target for this triple (no targets are registered)";
     return nullptr;
   }
-  Triple::ArchType Arch = Triple(TT).getArch();
+  Triple::ArchType Arch = TT.getArch();
   auto ArchMatch = [&](const Target &T) { return T.ArchMatchFn(Arch); };
   auto I = find_if(targets(), ArchMatch);
 
   if (I == targets().end()) {
-    Error = ("No available targets are compatible with triple \"" + TT + "\"")
-                .str();
+    Error =
+        "No available targets are compatible with triple \"" + TT.str() + "\"";
     return nullptr;
   }
 
diff --git a/llvm/lib/Object/ELFObjectFile.cpp b/llvm/lib/Object/ELFObjectFile.cpp
index ac25d76709726..d0897c62b3e8e 100644
--- a/llvm/lib/Object/ELFObjectFile.cpp
+++ b/llvm/lib/Object/ELFObjectFile.cpp
@@ -781,7 +781,7 @@ void ELFObjectFileBase::setARMSubArch(Triple &TheTriple) const {
 std::vector<ELFPltEntry> ELFObjectFileBase::getPltEntries() const {
   std::string Err;
   const auto Triple = makeTriple();
-  const auto *T = TargetRegistry::lookupTarget(Triple.str(), Err);
+  const auto *T = TargetRegistry::lookupTarget(Triple, Err);
   if (!T)
     return {};
   uint32_t JumpSlotReloc = 0, GlobDatReloc = 0;
diff --git a/llvm/lib/Object/ModuleSymbolTable.cpp b/llvm/lib/Object/ModuleSymbolTable.cpp
index 54e654a0d121c..1706772912772 100644
--- a/llvm/lib/Object/ModuleSymbolTable.cpp
+++ b/llvm/lib/Object/ModuleSymbolTable.cpp
@@ -78,7 +78,7 @@ initializeRecordStreamer(const Module &M,
 
   std::string Err;
   const Triple TT(M.getTargetTriple());
-  const Target *T = TargetRegistry::lookupTarget(TT.str(), Err);
+  const Target *T = TargetRegistry::lookupTarget(TT, Err);
   assert(T && T->hasMCAsmParser());
 
   std::unique_ptr<MCRegisterInfo> MRI(T->createMCRegInfo(TT.str()));
diff --git a/llvm/tools/llvm-dwarfdump/llvm-dwarfdump.cpp b/llvm/tools/llvm-dwarfdump/llvm-dwarfdump.cpp
index d63c51566e80c..f099bf5c1c962 100644
--- a/llvm/tools/llvm-dwarfdump/llvm-dwarfdump.cpp
+++ b/llvm/tools/llvm-dwarfdump/llvm-dwarfdump.cpp
@@ -661,8 +661,7 @@ createRegInfo(const object::ObjectFile &Obj) {
   TT.setVendor(Triple::UnknownVendor);
   TT.setOS(Triple::UnknownOS);
   std::string TargetLookupError;
-  const Target *TheTarget =
-      TargetRegistry::lookupTarget(TT.str(), TargetLookupError);
+  const Target *TheTarget = TargetRegistry::lookupTarget(TT, TargetLookupError);
   if (!TargetLookupError.empty())
     return nullptr;
   MCRegInfo.reset(TheTarget->createMCRegInfo(TT.str()));
diff --git a/llvm/unittests/DebugInfo/DWARF/DwarfUtils.cpp b/llvm/unittests/DebugInfo/DWARF/DwarfUtils.cpp
index c35b3b6f5365b..d7bbecb466a67 100644
--- a/llvm/unittests/DebugInfo/DWARF/DwarfUtils.cpp
+++ b/llvm/unittests/DebugInfo/DWARF/DwarfUtils.cpp
@@ -50,6 +50,6 @@ Triple llvm::dwarf::utils::getDefaultTargetTripleForAddrSize(uint8_t AddrSize) {
 bool llvm::dwarf::utils::isConfigurationSupported(Triple &T) {
   initLLVMIfNeeded();
   std::string Err;
-  const Target *TheTarget = TargetRegistry::lookupTarget(T.getTriple(), Err);
+  const Target *TheTarget = TargetRegistry::lookupTarget(T, Err);
   return TheTarget && TheTarget->hasMCAsmBackend();
 }
diff --git a/llvm/unittests/DebugInfo/LogicalView/CodeViewReaderTest.cpp b/llvm/unittests/DebugInfo/LogicalView/CodeViewReaderTest.cpp
index 7639f001e30dd..c93a79094dce9 100644
--- a/llvm/unittests/DebugInfo/LogicalView/CodeViewReaderTest.cpp
+++ b/llvm/unittests/DebugInfo/LogicalView/CodeViewReaderTest.cpp
@@ -553,7 +553,7 @@ TEST(LogicalViewTest, CodeViewReader) {
   TT.setOS(Triple::UnknownOS);
 
   std::string TargetLookupError;
-  if (!TargetRegistry::lookupTarget(std::string(TT.str()), TargetLookupError))
+  if (!TargetRegistry::lookupTarget(TT, TargetLookupError))
     return;
 
   SmallString<128> InputsDir = unittest::getInputFileDirectory(TestMainArgv0);
diff --git a/llvm/unittests/DebugInfo/LogicalView/DWARFReaderTest.cpp b/llvm/unittests/DebugInfo/LogicalView/DWARFReaderTest.cpp
index a1bd5dee35656..c062c15481da9 100644
--- a/llvm/unittests/DebugInfo/LogicalView/DWARFReaderTest.cpp
+++ b/llvm/unittests/DebugInfo/LogicalView/DWARFReaderTest.cpp
@@ -338,7 +338,7 @@ TEST(LogicalViewTest, DWARFReader) {
   TT.setOS(Triple::UnknownOS);
 
   std::string TargetLookupError;
-  if (!TargetRegistry::lookupTarget(std::string(TT.str()), TargetLookupError))
+  if (!TargetRegistry::lookupTarget(TT, TargetLookupError))
     GTEST_SKIP();
 
   SmallString<128> InputsDir = unittest::getInputFileDirectory(TestMainArgv0);
diff --git a/llvm/unittests/tools/llvm-mca/MCATestBase.cpp b/llvm/unittests/tools/llvm-mca/MCATestBase.cpp
index 4a39f5e663f23..cd3258ef96d64 100644
--- a/llvm/unittests/tools/llvm-mca/MCATestBase.cpp
+++ b/llvm/unittests/tools/llvm-mca/MCATestBase.cpp
@@ -14,7 +14,7 @@ using namespace mca;
 
 const Target *MCATestBase::getLLVMTarget() const {
   std::string Error;
-  return TargetRegistry::lookupTarget(TheTriple.getTriple(), Error);
+  return TargetRegistry::lookupTarget(TheTriple, Error);
 }
 
 mca::PipelineOptions MCATestBase::getDefaultPipelineOptions() {

>From 148e13837841317f0c70160336e06155ef030ccc Mon Sep 17 00:00:00 2001
From: Nikita Popov <npopov at redhat.com>
Date: Wed, 5 Mar 2025 16:44:49 +0100
Subject: [PATCH 4/4] try to fix flang

---
 flang/lib/Frontend/FrontendActions.cpp | 4 ++--
 1 file changed, 2 insertions(+), 2 deletions(-)

diff --git a/flang/lib/Frontend/FrontendActions.cpp b/flang/lib/Frontend/FrontendActions.cpp
index 76d329d043731..72a656b3627f5 100644
--- a/flang/lib/Frontend/FrontendActions.cpp
+++ b/flang/lib/Frontend/FrontendActions.cpp
@@ -1389,10 +1389,10 @@ void CodeGenAction::executeAction() {
   // given on the command-line).
   llvm::TargetMachine &targetMachine = ci.getTargetMachine();
 
-  const std::string &theTriple = targetMachine.getTargetTriple().str();
+  const llvm::Triple &theTriple = targetMachine.getTargetTriple();
 
   if (llvmModule->getTargetTriple() != theTriple) {
-    diags.Report(clang::diag::warn_fe_override_module) << theTriple;
+    diags.Report(clang::diag::warn_fe_override_module) << theTriple.str();
   }
 
   // Always set the triple and data layout, to make sure they match and are set.



More information about the flang-commits mailing list