Skip to content

Commit 979c275

Browse files
authored
[IR] Store Triple in Module (NFC) (#129868)
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.
1 parent f01e760 commit 979c275

File tree

111 files changed

+244
-241
lines changed

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

111 files changed

+244
-241
lines changed

clang/lib/CodeGen/BackendUtil.cpp

+1-1
Original file line numberDiff line numberDiff line change
@@ -595,7 +595,7 @@ static void setCommandLineOpts(const CodeGenOptions &CodeGenOpts) {
595595
void EmitAssemblyHelper::CreateTargetMachine(bool MustCreateTM) {
596596
// Create the TargetMachine for generating code.
597597
std::string Error;
598-
std::string Triple = TheModule->getTargetTriple();
598+
std::string Triple = TheModule->getTargetTriple().str();
599599
const llvm::Target *TheTarget = TargetRegistry::lookupTarget(Triple, Error);
600600
if (!TheTarget) {
601601
if (MustCreateTM)

clang/lib/CodeGen/CodeGenAction.cpp

+3-3
Original file line numberDiff line numberDiff line change
@@ -1032,7 +1032,7 @@ CodeGenAction::loadModule(MemoryBufferRef MBRef) {
10321032
// linker using merged object file.
10331033
if (!Bm) {
10341034
auto M = std::make_unique<llvm::Module>("empty", *VMContext);
1035-
M->setTargetTriple(CI.getTargetOpts().Triple);
1035+
M->setTargetTriple(Triple(CI.getTargetOpts().Triple));
10361036
return M;
10371037
}
10381038
Expected<std::unique_ptr<llvm::Module>> MOrErr =
@@ -1123,10 +1123,10 @@ void CodeGenAction::ExecuteAction() {
11231123
return;
11241124

11251125
const TargetOptions &TargetOpts = CI.getTargetOpts();
1126-
if (TheModule->getTargetTriple() != TargetOpts.Triple) {
1126+
if (TheModule->getTargetTriple().str() != TargetOpts.Triple) {
11271127
Diagnostics.Report(SourceLocation(), diag::warn_fe_override_module)
11281128
<< TargetOpts.Triple;
1129-
TheModule->setTargetTriple(TargetOpts.Triple);
1129+
TheModule->setTargetTriple(Triple(TargetOpts.Triple));
11301130
}
11311131

11321132
EmbedObject(TheModule.get(), CodeGenOpts, Diagnostics);

clang/lib/CodeGen/ModuleBuilder.cpp

+1-1
Original file line numberDiff line numberDiff line change
@@ -151,7 +151,7 @@ namespace {
151151
void Initialize(ASTContext &Context) override {
152152
Ctx = &Context;
153153

154-
M->setTargetTriple(Ctx->getTargetInfo().getTriple().getTriple());
154+
M->setTargetTriple(Ctx->getTargetInfo().getTriple());
155155
M->setDataLayout(Ctx->getTargetInfo().getDataLayoutString());
156156
const auto &SDKVersion = Ctx->getTargetInfo().getSDKVersion();
157157
if (!SDKVersion.empty())

clang/lib/CodeGen/ObjectFilePCHContainerWriter.cpp

+2-2
Original file line numberDiff line numberDiff line change
@@ -255,7 +255,7 @@ class PCHContainerGenerator : public ASTConsumer {
255255
if (Diags.hasErrorOccurred())
256256
return;
257257

258-
M->setTargetTriple(Ctx.getTargetInfo().getTriple().getTriple());
258+
M->setTargetTriple(Ctx.getTargetInfo().getTriple());
259259
M->setDataLayout(Ctx.getTargetInfo().getDataLayoutString());
260260

261261
// PCH files don't have a signature field in the control block,
@@ -274,7 +274,7 @@ class PCHContainerGenerator : public ASTConsumer {
274274
// Ensure the target exists.
275275
std::string Error;
276276
auto Triple = Ctx.getTargetInfo().getTriple();
277-
if (!llvm::TargetRegistry::lookupTarget(Triple.getTriple(), Error))
277+
if (!llvm::TargetRegistry::lookupTarget(Triple, Error))
278278
llvm::report_fatal_error(llvm::Twine(Error));
279279

280280
// Emit the serialized Clang AST into its own section.

clang/lib/Interpreter/DeviceOffload.cpp

+1-1
Original file line numberDiff line numberDiff line change
@@ -83,7 +83,7 @@ llvm::Expected<llvm::StringRef> IncrementalCUDADeviceParser::GeneratePTX() {
8383
std::error_code());
8484
llvm::TargetOptions TO = llvm::TargetOptions();
8585
llvm::TargetMachine *TargetMachine = Target->createTargetMachine(
86-
PTU.TheModule->getTargetTriple(), TargetOpts.CPU, "", TO,
86+
PTU.TheModule->getTargetTriple().str(), TargetOpts.CPU, "", TO,
8787
llvm::Reloc::Model::PIC_);
8888
PTU.TheModule->setDataLayout(TargetMachine->createDataLayout());
8989

clang/tools/clang-fuzzer/handle-llvm/handle_llvm.cpp

+2-2
Original file line numberDiff line numberDiff line change
@@ -127,8 +127,8 @@ static std::string OptLLVM(const std::string &IR, CodeGenOptLevel OLvl) {
127127
ErrorAndExit(E);
128128

129129
std::unique_ptr<TargetMachine> TM(TheTarget->createTargetMachine(
130-
M->getTargetTriple(), codegen::getCPUStr(), codegen::getFeaturesStr(),
131-
Options, codegen::getExplicitRelocModel(),
130+
M->getTargetTriple().str(), codegen::getCPUStr(),
131+
codegen::getFeaturesStr(), Options, codegen::getExplicitRelocModel(),
132132
codegen::getExplicitCodeModel(), OLvl));
133133
if (!TM)
134134
ErrorAndExit("Could not create target machine");

clang/tools/clang-linker-wrapper/ClangLinkerWrapper.cpp

+5-5
Original file line numberDiff line numberDiff line change
@@ -627,11 +627,11 @@ Expected<StringRef> compileModule(Module &M, OffloadKind Kind) {
627627
return createStringError(Msg);
628628

629629
auto Options =
630-
codegen::InitTargetOptionsFromCodeGenFlags(Triple(M.getTargetTriple()));
630+
codegen::InitTargetOptionsFromCodeGenFlags(M.getTargetTriple());
631631
StringRef CPU = "";
632632
StringRef Features = "";
633633
std::unique_ptr<TargetMachine> TM(
634-
T->createTargetMachine(M.getTargetTriple(), CPU, Features, Options,
634+
T->createTargetMachine(M.getTargetTriple().str(), CPU, Features, Options,
635635
Reloc::PIC_, M.getCodeModel()));
636636

637637
if (M.getDataLayout().isDefault())
@@ -650,7 +650,7 @@ Expected<StringRef> compileModule(Module &M, OffloadKind Kind) {
650650
auto OS = std::make_unique<llvm::raw_fd_ostream>(FD, true);
651651

652652
legacy::PassManager CodeGenPasses;
653-
TargetLibraryInfoImpl TLII(Triple(M.getTargetTriple()));
653+
TargetLibraryInfoImpl TLII(M.getTargetTriple());
654654
CodeGenPasses.add(new TargetLibraryInfoWrapperPass(TLII));
655655
if (TM->addPassesToEmitFile(CodeGenPasses, *OS, nullptr,
656656
CodeGenFileType::ObjectFile))
@@ -674,8 +674,8 @@ wrapDeviceImages(ArrayRef<std::unique_ptr<MemoryBuffer>> Buffers,
674674

675675
LLVMContext Context;
676676
Module M("offload.wrapper.module", Context);
677-
M.setTargetTriple(
678-
Args.getLastArgValue(OPT_host_triple_EQ, sys::getDefaultTargetTriple()));
677+
M.setTargetTriple(Triple(
678+
Args.getLastArgValue(OPT_host_triple_EQ, sys::getDefaultTargetTriple())));
679679

680680
switch (Kind) {
681681
case OFK_OpenMP:

clang/unittests/Interpreter/InterpreterExtensionsTest.cpp

+1-1
Original file line numberDiff line numberDiff line change
@@ -61,7 +61,7 @@ class InterpreterExtensionsTest : public InterpreterTestBase {
6161
TT.setOS(llvm::Triple::UnknownOS);
6262

6363
std::string UnusedErr;
64-
return llvm::TargetRegistry::lookupTarget(TT.str(), UnusedErr);
64+
return llvm::TargetRegistry::lookupTarget(TT, UnusedErr);
6565
}
6666
};
6767

flang/lib/Frontend/FrontendActions.cpp

+2-2
Original file line numberDiff line numberDiff line change
@@ -1389,10 +1389,10 @@ void CodeGenAction::executeAction() {
13891389
// given on the command-line).
13901390
llvm::TargetMachine &targetMachine = ci.getTargetMachine();
13911391

1392-
const std::string &theTriple = targetMachine.getTargetTriple().str();
1392+
const llvm::Triple &theTriple = targetMachine.getTargetTriple();
13931393

13941394
if (llvmModule->getTargetTriple() != theTriple) {
1395-
diags.Report(clang::diag::warn_fe_override_module) << theTriple;
1395+
diags.Report(clang::diag::warn_fe_override_module) << theTriple.str();
13961396
}
13971397

13981398
// Always set the triple and data layout, to make sure they match and are set.

lldb/source/Plugins/Instruction/MIPS/EmulateInstructionMIPS.cpp

+2-2
Original file line numberDiff line numberDiff line change
@@ -67,7 +67,7 @@ EmulateInstructionMIPS::EmulateInstructionMIPS(
6767
std::string Status;
6868
llvm::Triple triple = arch.GetTriple();
6969
const llvm::Target *target =
70-
llvm::TargetRegistry::lookupTarget(triple.getTriple(), Status);
70+
llvm::TargetRegistry::lookupTarget(triple, Status);
7171

7272
/*
7373
* If we fail to get the target then we haven't registered it. The
@@ -84,7 +84,7 @@ EmulateInstructionMIPS::EmulateInstructionMIPS(
8484
LLVMInitializeMipsAsmPrinter();
8585
LLVMInitializeMipsTargetMC();
8686
LLVMInitializeMipsDisassembler();
87-
target = llvm::TargetRegistry::lookupTarget(triple.getTriple(), Status);
87+
target = llvm::TargetRegistry::lookupTarget(triple, Status);
8888
}
8989
#endif
9090

lldb/source/Plugins/Instruction/MIPS64/EmulateInstructionMIPS64.cpp

+2-2
Original file line numberDiff line numberDiff line change
@@ -67,7 +67,7 @@ EmulateInstructionMIPS64::EmulateInstructionMIPS64(
6767
std::string Status;
6868
llvm::Triple triple = arch.GetTriple();
6969
const llvm::Target *target =
70-
llvm::TargetRegistry::lookupTarget(triple.getTriple(), Status);
70+
llvm::TargetRegistry::lookupTarget(triple, Status);
7171

7272
/*
7373
* If we fail to get the target then we haven't registered it. The
@@ -84,7 +84,7 @@ EmulateInstructionMIPS64::EmulateInstructionMIPS64(
8484
LLVMInitializeMipsAsmPrinter();
8585
LLVMInitializeMipsTargetMC();
8686
LLVMInitializeMipsDisassembler();
87-
target = llvm::TargetRegistry::lookupTarget(triple.getTriple(), Status);
87+
target = llvm::TargetRegistry::lookupTarget(triple, Status);
8888
}
8989
#endif
9090

llvm/examples/OrcV2Examples/LLJITWithThinLTOSummaries/LLJITWithThinLTOSummaries.cpp

+1-1
Original file line numberDiff line numberDiff line change
@@ -207,7 +207,7 @@ int main(int Argc, char *Argv[]) {
207207
ExitOnErr(JITTargetMachineBuilder::detectHost()));
208208
} else {
209209
Builder.setJITTargetMachineBuilder(
210-
JITTargetMachineBuilder(Triple(M.getTargetTriple())));
210+
JITTargetMachineBuilder(M.getTargetTriple()));
211211
}
212212
if (!M.getDataLayout().getStringRepresentation().empty())
213213
Builder.setDataLayout(M.getDataLayout());

llvm/include/llvm/ExecutionEngine/Orc/ExecutionUtils.h

+1-1
Original file line numberDiff line numberDiff line change
@@ -104,7 +104,7 @@ class StaticInitGVIterator {
104104

105105
StaticInitGVIterator(Module &M)
106106
: I(M.global_values().begin()), E(M.global_values().end()),
107-
ObjFmt(Triple(M.getTargetTriple()).getObjectFormat()) {
107+
ObjFmt(M.getTargetTriple().getObjectFormat()) {
108108
if (I != E) {
109109
if (!isStaticInitGlobal(*I))
110110
moveToNextStaticInitGlobal();

llvm/include/llvm/Frontend/OpenMP/OMPIRBuilder.h

+1-1
Original file line numberDiff line numberDiff line change
@@ -479,7 +479,7 @@ class OpenMPIRBuilder {
479479
/// not have an effect on \p M (see initialize)
480480
OpenMPIRBuilder(Module &M)
481481
: M(M), Builder(M.getContext()), OffloadInfoManager(this),
482-
T(Triple(M.getTargetTriple())) {}
482+
T(M.getTargetTriple()) {}
483483
~OpenMPIRBuilder();
484484

485485
class AtomicInfo : public llvm::AtomicInfo {

llvm/include/llvm/IR/Module.h

+7-5
Original file line numberDiff line numberDiff line change
@@ -31,6 +31,7 @@
3131
#include "llvm/IR/SymbolTableListTraits.h"
3232
#include "llvm/Support/CBindingWrapping.h"
3333
#include "llvm/Support/CodeGen.h"
34+
#include "llvm/TargetParser/Triple.h"
3435
#include <cstddef>
3536
#include <cstdint>
3637
#include <iterator>
@@ -189,8 +190,10 @@ class LLVM_ABI Module {
189190
std::string ModuleID; ///< Human readable identifier for the module
190191
std::string SourceFileName; ///< Original source file name for module,
191192
///< recorded in bitcode.
192-
std::string TargetTriple; ///< Platform target triple Module compiled on
193-
///< Format: (arch)(sub)-(vendor)-(sys0-(abi)
193+
/// Platform target triple Module compiled on
194+
/// Format: (arch)(sub)-(vendor)-(sys)-(abi)
195+
// FIXME: Default construction is not the same as empty triple :(
196+
Triple TargetTriple = Triple("");
194197
NamedMDSymTabType NamedMDSymTab; ///< NamedMDNode names.
195198
DataLayout DL; ///< DataLayout associated with the module
196199
StringMap<unsigned>
@@ -294,8 +297,7 @@ class LLVM_ABI Module {
294297
const DataLayout &getDataLayout() const { return DL; }
295298

296299
/// Get the target triple which is a string describing the target host.
297-
/// @returns a string containing the target triple.
298-
const std::string &getTargetTriple() const { return TargetTriple; }
300+
const Triple &getTargetTriple() const { return TargetTriple; }
299301

300302
/// Get the global data context.
301303
/// @returns LLVMContext - a container for LLVM's global information
@@ -338,7 +340,7 @@ class LLVM_ABI Module {
338340
void setDataLayout(const DataLayout &Other);
339341

340342
/// Set the target triple.
341-
void setTargetTriple(StringRef T) { TargetTriple = std::string(T); }
343+
void setTargetTriple(Triple T) { TargetTriple = std::move(T); }
342344

343345
/// Set the module-scope inline assembly blocks.
344346
/// A trailing newline is added if the input doesn't have one.

llvm/include/llvm/LTO/legacy/LTOModule.h

+2-6
Original file line numberDiff line numberDiff line change
@@ -118,14 +118,10 @@ struct LTOModule {
118118
std::unique_ptr<Module> takeModule() { return std::move(Mod); }
119119

120120
/// Return the Module's target triple.
121-
const std::string &getTargetTriple() {
122-
return getModule().getTargetTriple();
123-
}
121+
const Triple &getTargetTriple() { return getModule().getTargetTriple(); }
124122

125123
/// Set the Module's target triple.
126-
void setTargetTriple(StringRef Triple) {
127-
getModule().setTargetTriple(Triple);
128-
}
124+
void setTargetTriple(Triple T) { getModule().setTargetTriple(T); }
129125

130126
/// Get the number of symbols
131127
uint32_t getSymbolCount() {

llvm/include/llvm/MC/TargetRegistry.h

+12-1
Original file line numberDiff line numberDiff line change
@@ -693,12 +693,23 @@ struct TargetRegistry {
693693

694694
static iterator_range<iterator> targets();
695695

696+
/// lookupTarget - Lookup a target based on a target triple.
697+
///
698+
/// \param TripleStr - The triple to use for finding a target.
699+
/// \param Error - On failure, an error string describing why no target was
700+
/// found.
701+
// TODO: Drop this in favor of the method accepting Triple.
702+
static const Target *lookupTarget(StringRef TripleStr, std::string &Error) {
703+
return lookupTarget(Triple(TripleStr), Error);
704+
}
705+
696706
/// lookupTarget - Lookup a target based on a target triple.
697707
///
698708
/// \param Triple - The triple to use for finding a target.
699709
/// \param Error - On failure, an error string describing why no target was
700710
/// found.
701-
static const Target *lookupTarget(StringRef Triple, std::string &Error);
711+
static const Target *lookupTarget(const Triple &TheTriple,
712+
std::string &Error);
702713

703714
/// lookupTarget - Lookup a target based on an architecture name
704715
/// and a target triple. If the architecture name is non-empty,

llvm/include/llvm/TargetParser/Triple.h

+3
Original file line numberDiff line numberDiff line change
@@ -463,6 +463,9 @@ class Triple {
463463

464464
const std::string &getTriple() const { return Data; }
465465

466+
/// Whether the triple is empty / default constructed.
467+
bool empty() const { return Data.empty(); }
468+
466469
/// Get the architecture (first) component of the triple.
467470
StringRef getArchName() const;
468471

llvm/lib/Analysis/DXILMetadataAnalysis.cpp

+1-1
Original file line numberDiff line numberDiff line change
@@ -24,7 +24,7 @@ using namespace dxil;
2424

2525
static ModuleMetadataInfo collectMetadataInfo(Module &M) {
2626
ModuleMetadataInfo MMDAI;
27-
Triple TT(Triple(M.getTargetTriple()));
27+
const Triple &TT = M.getTargetTriple();
2828
MMDAI.DXILVersion = TT.getDXILVersion();
2929
MMDAI.ShaderModelVersion = TT.getOSVersion();
3030
MMDAI.ShaderProfile = TT.getEnvironment();

llvm/lib/Analysis/Lint.cpp

+3-3
Original file line numberDiff line numberDiff line change
@@ -127,7 +127,7 @@ class Lint : public InstVisitor<Lint> {
127127

128128
public:
129129
Module *Mod;
130-
Triple TT;
130+
const Triple &TT;
131131
const DataLayout *DL;
132132
AliasAnalysis *AA;
133133
AssumptionCache *AC;
@@ -139,8 +139,8 @@ class Lint : public InstVisitor<Lint> {
139139

140140
Lint(Module *Mod, const DataLayout *DL, AliasAnalysis *AA,
141141
AssumptionCache *AC, DominatorTree *DT, TargetLibraryInfo *TLI)
142-
: Mod(Mod), TT(Triple::normalize(Mod->getTargetTriple())), DL(DL), AA(AA),
143-
AC(AC), DT(DT), TLI(TLI), MessagesStr(Messages) {}
142+
: Mod(Mod), TT(Mod->getTargetTriple()), DL(DL), AA(AA), AC(AC), DT(DT),
143+
TLI(TLI), MessagesStr(Messages) {}
144144

145145
void WriteValues(ArrayRef<const Value *> Vs) {
146146
for (const Value *V : Vs) {

llvm/lib/Analysis/TargetLibraryInfo.cpp

+3-4
Original file line numberDiff line numberDiff line change
@@ -118,7 +118,7 @@ static bool hasBcmp(const Triple &TT) {
118118
return TT.isOSFreeBSD() || TT.isOSSolaris();
119119
}
120120

121-
static bool isCallingConvCCompatible(CallingConv::ID CC, StringRef TT,
121+
static bool isCallingConvCCompatible(CallingConv::ID CC, const Triple &TT,
122122
FunctionType *FuncTy) {
123123
switch (CC) {
124124
default:
@@ -131,7 +131,7 @@ static bool isCallingConvCCompatible(CallingConv::ID CC, StringRef TT,
131131

132132
// The iOS ABI diverges from the standard in some cases, so for now don't
133133
// try to simplify those calls.
134-
if (Triple(TT).isiOS())
134+
if (TT.isiOS())
135135
return false;
136136

137137
if (!FuncTy->getReturnType()->isPointerTy() &&
@@ -1446,8 +1446,7 @@ TargetLibraryInfoImpl::getVectorMappingInfo(StringRef F, const ElementCount &VF,
14461446
TargetLibraryInfo TargetLibraryAnalysis::run(const Function &F,
14471447
FunctionAnalysisManager &) {
14481448
if (!BaselineInfoImpl)
1449-
BaselineInfoImpl =
1450-
TargetLibraryInfoImpl(Triple(F.getParent()->getTargetTriple()));
1449+
BaselineInfoImpl = TargetLibraryInfoImpl(F.getParent()->getTargetTriple());
14511450
return TargetLibraryInfo(*BaselineInfoImpl, &F);
14521451
}
14531452

llvm/lib/AsmParser/LLParser.cpp

+2-2
Original file line numberDiff line numberDiff line change
@@ -522,7 +522,7 @@ bool LLParser::parseTargetDefinitions(DataLayoutCallbackTy DataLayoutCallback) {
522522
// Run the override callback to potentially change the data layout string, and
523523
// parse the data layout string.
524524
if (auto LayoutOverride =
525-
DataLayoutCallback(M->getTargetTriple(), TentativeDLStr)) {
525+
DataLayoutCallback(M->getTargetTriple().str(), TentativeDLStr)) {
526526
TentativeDLStr = *LayoutOverride;
527527
DLStrLoc = {};
528528
}
@@ -646,7 +646,7 @@ bool LLParser::parseTargetDefinition(std::string &TentativeDLStr,
646646
if (parseToken(lltok::equal, "expected '=' after target triple") ||
647647
parseStringConstant(Str))
648648
return true;
649-
M->setTargetTriple(Str);
649+
M->setTargetTriple(Triple(Str));
650650
return false;
651651
case lltok::kw_datalayout:
652652
Lex.Lex();

llvm/lib/Bitcode/Reader/BitcodeReader.cpp

+3-3
Original file line numberDiff line numberDiff line change
@@ -4530,12 +4530,12 @@ Error BitcodeReader::parseModule(uint64_t ResumeBit,
45304530

45314531
// Auto-upgrade the layout string
45324532
TentativeDataLayoutStr = llvm::UpgradeDataLayoutString(
4533-
TentativeDataLayoutStr, TheModule->getTargetTriple());
4533+
TentativeDataLayoutStr, TheModule->getTargetTriple().str());
45344534

45354535
// Apply override
45364536
if (Callbacks.DataLayout) {
45374537
if (auto LayoutOverride = (*Callbacks.DataLayout)(
4538-
TheModule->getTargetTriple(), TentativeDataLayoutStr))
4538+
TheModule->getTargetTriple().str(), TentativeDataLayoutStr))
45394539
TentativeDataLayoutStr = *LayoutOverride;
45404540
}
45414541

@@ -4719,7 +4719,7 @@ Error BitcodeReader::parseModule(uint64_t ResumeBit,
47194719
std::string S;
47204720
if (convertToString(Record, 0, S))
47214721
return error("Invalid record");
4722-
TheModule->setTargetTriple(S);
4722+
TheModule->setTargetTriple(Triple(S));
47234723
break;
47244724
}
47254725
case bitc::MODULE_CODE_DATALAYOUT: { // DATALAYOUT: [strchr x N]

0 commit comments

Comments
 (0)